Java Code Examples for org.hibernate.Session.flush()

The following are Jave code examples for showing how to use flush() of the org.hibernate.Session class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: lams   File: SpringSessionSynchronization.java   View Source Code Vote up 7 votes
@Override
public void beforeCommit(boolean readOnly) throws DataAccessException {
	if (!readOnly) {
		Session session = getCurrentSession();
		// Read-write transaction -> flush the Hibernate Session.
		// Further check: only flush when not FlushMode.MANUAL.
		if (!session.getFlushMode().equals(FlushMode.MANUAL)) {
			try {
				SessionFactoryUtils.logger.debug("Flushing Hibernate Session on transaction synchronization");
				session.flush();
			}
			catch (HibernateException ex) {
				throw SessionFactoryUtils.convertHibernateAccessException(ex);
			}
		}
	}
}
 
Example 2
Project: bdf2   File: JobMaintain.java   View Source Code Vote up 6 votes
@DataProvider
public Collection<JobCalendar> loadCalendars(String jobId){
	String hql="from "+JobCalendarRelation.class.getName()+" j where j.jobId=:jobId";
	Map<String,Object> map=new HashMap<String,Object>();
	map.put("jobId",jobId);
	List<JobCalendar> result=new ArrayList<JobCalendar>();
	List<JobCalendarRelation> relations=this.query(hql, map);
	Session session=this.getSessionFactory().openSession();
	try{
		for(JobCalendarRelation r:relations){
			result.add((JobCalendar)session.get(JobCalendar.class, r.getCalendarId()));
		}			
	}finally{
		session.flush();
		session.close();
	}
	return result;
}
 
Example 3
Project: bdf2   File: JobMaintain.java   View Source Code Vote up 6 votes
@DataResolver
public void saveJobParameters(Collection<JobParameter> parameters){
	Session session=this.getSessionFactory().openSession();
	try{
		for(JobParameter p:parameters){
			EntityState state=EntityUtils.getState(p);
			if(state.equals(EntityState.NEW)){
				p.setId(UUID.randomUUID().toString());
				session.save(p);
			}
			if(state.equals(EntityState.MODIFIED)){
				session.update(p);
			}
			if(state.equals(EntityState.DELETED)){
				session.delete(p);
			}
		}
	}finally{
		session.flush();
		session.close();
	}
}
 
Example 4
Project: bdf2   File: InternalMessageSender.java   View Source Code Vote up 6 votes
public void send(MessagePacket message) {
	Collection<IUser> toUsers=message.getTo();
	if(toUsers==null || toUsers.size()==0){
		throw new IllegalAddException("You must define at least one message recipient!");
	}
	Collection<IUser> ccUsers=message.getCc();
	if(ccUsers!=null && ccUsers.size()>0){
		toUsers.addAll(ccUsers);
	}
	Session session=this.getSessionFactory().openSession();
	try{
		for(IUser user:toUsers){
			Message msg=new Message();
			msg.setId(UUID.randomUUID().toString());
			msg.setSendDate(new Date());
			msg.setSender(message.getSender().getUsername());
			msg.setReply(false);
			msg.setRead(false);
			msg.setContent(message.getContent());
			msg.setTitle(message.getTitle());
			msg.setReceiver(user.getUsername());
			session.save(msg);
		}
	}finally{
		session.flush();
		session.close();
	}
}
 
Example 5
Project: sjk   File: AppHistory4IndexDaoImpl.java   View Source Code Vote up 6 votes
/**
 * 设置appStatus 状态 为可删除 状态 3,索引状态 indexStatus为 -1
 */
@Override
public int updateAppStatus2Del(List<Integer> ids) {
    Session session = null;

    try {
        session = this.sessions.openSession();

        String hql = "update AppHistory4Index set appStatus=3,indexStatus=-1,lastOpTime=:lastOpTime where appId in (:appIds)";
        Query query = session.createQuery(hql);
        query.setParameterList("appIds", ids);
        query.setTimestamp("lastOpTime", new Date());

        return query.executeUpdate();

    } catch (Exception e) {
        logger.error("error:", e);
        return 0;
    } finally {
        if (session != null && session.isOpen()) {
            session.flush();
            session.clear();
            session.close();
        }
    }

}
 
Example 6
Project: sjk   File: AppHistory4IndexDaoImpl.java   View Source Code Vote up 6 votes
@Override
public int update(List<Integer> ids) {
    Session session = null;
    try {
        session = this.sessions.openSession();
        // 设置状态 为更新
        // 需要重新索引
        String hql = "update AppHistory4Index set appStatus=2,indexStatus=0,lastOpTime=:lastOpTime where appId in (:appIds)";
        Query query = session.createQuery(hql);
        query.setParameterList("appIds", ids);
        query.setTimestamp("lastOpTime", new Date());

        return query.executeUpdate();

    } catch (Exception e) {
        logger.error("error:", e);
        return 0;
    } finally {
        if (session != null && session.isOpen()) {
            session.flush();
            session.clear();
            session.close();
        }
    }
}
 
Example 7
Project: sjk   File: MarketAppDaoImpl.java   View Source Code Vote up 6 votes
@Override
public List<MarketApp> getAllBigGameFromMarketApp() {
    String hqlStr = "from MarketApp a where a.catalog =100";
    List<MarketApp> list = null;

    Session session = null;
    try {
        session = sessionFactory.openSession();
        list = session.createQuery(hqlStr).list();
    } finally {
        session.flush();
        session.clear();
        session.close();
    }

    return list;
}
 
Example 8
Project: bdf2   File: ValidatorMaintain.java   View Source Code Vote up 6 votes
@DataResolver
public void saveValidatorEvents(Collection<ValidatorEvent> events){
	Session session=this.getSessionFactory().openSession();
	try{
		for(ValidatorEvent v:events){
			EntityState state=EntityUtils.getState(v);
			if(state.equals(EntityState.NEW)){
				v.setId(UUID.randomUUID().toString());
				session.save(v);
			}
			if(state.equals(EntityState.DELETED)){
				session.delete(v);
			}
			if(state.equals(EntityState.MODIFIED)){
				session.update(v);
			}
		}			
	}finally{
		session.flush();
		session.close();
	}
}
 
Example 9
Project: bdf2   File: ValidatorMaintain.java   View Source Code Vote up 6 votes
@DataResolver
public void saveValidatorProperties(Collection<ValidatorProperty> properties){
	Session session=this.getSessionFactory().openSession();
	try{
		for(ValidatorProperty v:properties){
			EntityState state=EntityUtils.getState(v);
			if(state.equals(EntityState.NEW)){
				v.setId(UUID.randomUUID().toString());
				session.save(v);
			}
			if(state.equals(EntityState.DELETED)){
				session.delete(v);
			}
			if(state.equals(EntityState.MODIFIED)){
				session.update(v);
			}
		}			
	}finally{
		session.flush();
		session.close();
	}
}
 
Example 10
Project: bdf2   File: AssignmentMaintain.java   View Source Code Vote up 5 votes
@DataResolver
public void saveAssignmentDefs(Collection<AssignmentDef> assignments){
	IUser user=ContextHolder.getLoginUser();
	if(user==null){
		throw new RuntimeException("Please login first!");
	}
	Session session=this.getSessionFactory().openSession();
	try{
		String companyId=user.getCompanyId();
		if(StringUtils.isNotEmpty(getFixedCompanyId())){
			companyId=getFixedCompanyId();
		}
		for(AssignmentDef def:assignments){
			EntityState state=EntityUtils.getState(def);
			if(state.equals(EntityState.NEW)){
				def.setId(UUID.randomUUID().toString());
				def.setCompanyId(companyId);
				session.save(def);
			}
			if(state.equals(EntityState.MODIFIED)){
				session.update(def);
			}
			if(state.equals(EntityState.DELETED)){
				for(IAssignmentProvider p:providers){
					if(p.isDisabled() || !p.getTypeId().equals(def.getType()))continue;
					p.deleteAssignmentInfos(def.getId());
				}
				session.delete(def);
			}
		}
	}finally{
		session.flush();
		session.close();
	}
}
 
Example 11
Project: bdf2   File: UserMaintain.java   View Source Code Vote up 5 votes
@DataResolver
public void saveUsers(Collection<DefaultUser> users) throws Exception {
	IUser loginuser=ContextHolder.getLoginUser();
	if(loginuser==null){
		throw new NoneLoginException("Please login first!");
	}
	String companyId=loginuser.getCompanyId();
	if(StringUtils.isNotEmpty(getFixedCompanyId())){
		companyId=getFixedCompanyId();
	}
	Session session = this.getSessionFactory().openSession();
	try{
		for (DefaultUser user : users) {
			EntityState state = EntityUtils.getState(user);
			if (state.equals(EntityState.NEW)) {
				String salt = String.valueOf(RandomUtils.nextInt(100));
				String password = passwordEncoder.encodePassword(
						user.getPassword(), salt);
				user.setPassword(password);
				user.setSalt(salt);
				user.setCompanyId(companyId);
				session.save(user);
			} else if (state.equals(EntityState.MODIFIED)) {
				session.update(user);
			} else if (state.equals(EntityState.DELETED)) {
				String userName = user.getUsername();
				roleService.deleteRoleMemeber(userName, MemberType.User);
				groupService.deleteGroupMemeber(userName, MemberType.User);
				positionService.deleteUserPositionByUser(userName);
				deptService.deleteUserDept(userName);
				session.delete(user);
			}
		}
	}finally{
		session.flush();
		session.close();
	}
}
 
Example 12
Project: bdf2   File: PositionMaintain.java   View Source Code Vote up 5 votes
@DataResolver
public void savePostions(final Collection<DefaultPosition> positions) {
	Session session = this.getSessionFactory().openSession();
	try {
		IUser user = ContextHolder.getLoginUser();
		if (user == null) {
			throw new NoneLoginException("Please login first");
		}
		String companyId = user.getCompanyId();
		if (StringUtils.isNotEmpty(getFixedCompanyId())) {
			companyId = getFixedCompanyId();
		}
		for (DefaultPosition position : positions) {
			EntityState state = EntityUtils.getState(position);
			if (state.equals(EntityState.NEW)) {
				position.setCompanyId(companyId);
				position.setCreateDate(new Date());
				session.save(position);
			} else if (state.equals(EntityState.MODIFIED)) {
				session.update(position);
			} else if (state.equals(EntityState.DELETED)) {
				roleService.deleteRoleMemeber(position.getId(), MemberType.Position);
				groupService.deleteGroupMemeber(position.getId(), MemberType.Position);
				positionService.deleteUserPosition(position.getId());
				session.delete(position);
			}
		}
	} finally {
		session.flush();
		session.close();
	}
}
 
Example 13
Project: bdf2   File: JobExecutionHistoryListener.java   View Source Code Vote up 5 votes
public void jobWasExecuted(JobExecutionContext context,
		JobExecutionException jobException) {
	JobDetail jobDetail = context.getJobDetail();
	if (!(jobDetail instanceof SpringBeanJobExecutorDetail)) {
		return;
	}
	JobDataMap map = jobDetail.getJobDataMap();
	if (!map.containsKey(IJobDefinitionService.JOB_DEFINITION_ID)) {
		return;
	}
	Date end = new Date();
	String exception = getExceptionStackMessage(jobException);
	JobHistory history = new JobHistory();
	history.setSuccessful(exception == null ? true : false);
	if (exception != null) {
		history.setExceptionMessage(exception.length() > 1500 ? exception
				.substring(0, 1500) : exception);
	}
	history.setEndDate(end);
	history.setStartDate((Date)map.get(START_DATE_KEY));
	history.setId(UUID.randomUUID().toString());
	history.setJobId(map.getString(IJobDefinitionService.JOB_DEFINITION_ID));
	Session session = getSessionFactory().openSession();
	try {
		session.save(history);
	} finally {
		session.flush();
		session.close();
	}
}
 
Example 14
Project: bdf2   File: HibernateDao.java   View Source Code Vote up 5 votes
public Collection<?> query(DetachedCriteria detachedCriteria, String dataSourceName) {
	Session session = this.getSessionFactory(dataSourceName).openSession();
	try {
		return detachedCriteria.getExecutableCriteria(session).list();
	} finally {
		session.flush();
		session.close();
	}
}
 
Example 15
Project: bdf2   File: JdbcTransactionManager.java   View Source Code Vote up 5 votes
private void clean(){
	Map<String,Session> sessionMap=ContextHolder.getHibernateSessionMap();
	if(sessionMap==null){
		return;
	}
	for(Session session:sessionMap.values()){
		if(session!=null && session.isOpen()){
			session.flush();
			session.close();
			session=null;
		}
	}
	sessionMap.clear();		
}
 
Example 16
Project: Homework   File: PetDaoImpl.java   View Source Code Vote up 4 votes
@Override
public void save(Pet pet, Session session, Transaction tx)
{
    session.persist(pet);
    session.flush();
}
 
Example 17
Project: Homework   File: PetDaoImpl.java   View Source Code Vote up 4 votes
@Override
public void delete(Pet pet, Session session, Transaction tx)
{
    session.delete(session.get(Pet.class, pet.getId()));
    session.flush();
}
 
Example 18
Project: Homework   File: PetTypeDaoImpl.java   View Source Code Vote up 4 votes
@Override
public void save(PetType petType, Session session, Transaction tx)
{
    session.save(petType);
    session.flush();
}
 
Example 19
Project: hibernate-ogm-ignite   File: ManyToOneTest.java   View Source Code Vote up 4 votes
@Test
public void testDefaultBiDirManyToOneCompositeKeyTest() throws Exception {
	Session session = openSession();
	Transaction transaction = session.beginTransaction();
	Court court = new Court();
	court.setId( new Court.CourtId() );
	court.getId().setCountryCode( "DE" );
	court.getId().setSequenceNo( 123 );
	court.setName( "Hamburg Court" );
	session.persist( court );
	Game game1 = new Game();
	game1.setId( new Game.GameId() );
	game1.getId().setCategory( "primary" );
	game1.getId().setSequenceNo( 456 );
	game1.setName( "The game" );
	game1.setPlayedOn( court );
	court.getGames().add( game1 );
	Game game2 = new Game();
	game2.setId( new Game.GameId() );
	game2.getId().setCategory( "primary" );
	game2.getId().setSequenceNo( 457 );
	game2.setName( "The other game" );
	game2.setPlayedOn( court );
	session.persist( game1 );
	session.persist( game2 );
	session.flush();
	transaction.commit();

	session.clear();

	transaction = session.beginTransaction();
	Court localCourt = session.get( Court.class, new Court.CourtId( "DE", 123 ) );
	assertThat( localCourt.getGames() ).hasSize( 2 );
	for ( Game game : localCourt.getGames() ) {
		session.delete( game );
	}
	localCourt.getGames().clear();
	session.delete( localCourt );
	transaction.commit();

	session.close();
}
 
Example 20
Project: lams   File: CustomizedOpenSessionInViewFilter.java   View Source Code Vote up 2 votes
/**
    * Close the given Session.
    * Note that this just applies in single session mode!
    * <p>
    * The default implementation delegates to SessionFactoryUtils'
    * closeSessionIfNecessary method.
    * <p>
    * Can be overridden in subclasses, e.g. for flushing the Session before
    * closing it. See class-level javadoc for a discussion of flush handling.
    * Note that you should also override getSession accordingly, to set
    * the flush mode to something else than NEVER.
    * 
    * @param session
    *            the Session used for filtering
    * @param sessionFactory
    *            the SessionFactory that this filter uses
    */
   protected void closeSession(Session session) {
session.flush();
SessionFactoryUtils.closeSession(session);
   }