Java Code Examples for org.hibernate.Session#update()

The following examples show how to use org.hibernate.Session#update() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CollectionReattachmentTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public void testUpdateOwnerAfterClear() {
	Session s = openSession();
	s.beginTransaction();
	Parent p = new Parent( "p" );
	p.getChildren().add( new Child( "c" ) );
	s.save( p );
	s.getTransaction().commit();
	s.close();

	s = openSession();
	s.beginTransaction();
	p = ( Parent ) s.get( Parent.class, "p" );
	// clear...
	s.clear();
	// now try to reattach...
	s.update( p );
	s.getTransaction().commit();
	s.close();

	s = openSession();
	s.beginTransaction();
	s.delete( p );
	s.getTransaction().commit();
	s.close();
}
 
Example 2
Source File: AutomationDAO.java    From document-management-system with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Update validation
 */
public void updateValidation(AutomationValidation av) throws DatabaseException {
	log.debug("updateAction({})", av);
	Session session = null;
	Transaction tx = null;

	try {
		session = HibernateUtil.getSessionFactory().openSession();
		tx = session.beginTransaction();
		session.update(av);
		HibernateUtil.commit(tx);
	} catch (HibernateException e) {
		HibernateUtil.rollback(tx);
		throw new DatabaseException(e.getMessage(), e);
	} finally {
		HibernateUtil.close(session);
	}

	log.debug("update: void");
}
 
Example 3
Source File: BaseAbstractDAO.java    From oim-fx with MIT License 6 votes vote down vote up
public <T> void updateList(final List<T> list) {
	if (null != list) {
		Session session = sessionBox.getCurrentSession();
		Transaction transaction = session.beginTransaction();
		try {
			int batch = 0;
			for (Object o : list) {
				session.update(o);
				batch++;
				if (batch == 50) {// 每50条批量提交一次。
					session.flush();
					session.clear();
					batch = 0;
				}
			}
			transaction.commit();
		} catch (Exception e) {
			e.printStackTrace();
			transaction.rollback();
		}
	}
}
 
Example 4
Source File: CronTabDAO.java    From document-management-system with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Set begin time
 */
public static void setLastBegin(long ctId) throws DatabaseException {
	log.debug("setLastBegin({})", ctId);
	Session session = null;
	Transaction tx = null;

	try {
		session = HibernateUtil.getSessionFactory().openSession();
		tx = session.beginTransaction();
		CronTab ct = (CronTab) session.load(CronTab.class, ctId);
		ct.setLastBegin(Calendar.getInstance());
		session.update(ct);
		HibernateUtil.commit(tx);
	} catch (HibernateException e) {
		HibernateUtil.rollback(tx);
		throw new DatabaseException(e.getMessage(), e);
	} finally {
		HibernateUtil.close(session);
	}

	log.debug("setLastBegin: void");
}
 
Example 5
Source File: TransactionalTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Test
public void testUpdateWithRefreshThenRollback() {
    Statistics stats = sessionFactory().getStatistics();
    Long id = null;
    Session s = openSession();
    s.beginTransaction();
    ItemTransactional item = new ItemTransactional( "data" );
    id = (Long) s.save( item );
    s.flush();
    s.getTransaction().commit();

    Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("item").getPutCount());

    s = openSession();
    s.beginTransaction();
    item = (ItemTransactional) s.get(ItemTransactional.class, id);
    item.setName("newdata");
    s.update(item);
    s.flush();
    s.refresh(item);
    s.getTransaction().rollback();
    s.clear();
    s.close();

    Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("item").getHitCount());
}
 
Example 6
Source File: InstructorRoles.java    From unitime with Apache License 2.0 6 votes vote down vote up
protected void delete(DepartmentalInstructor instructor, SessionContext context, Session hibSession) {
	if (instructor == null) return;
	
	if (instructor.getRole() == null) return;
	
	instructor.setRole(null);
	
	hibSession.update(instructor);
	
	ChangeLog.addChange(hibSession,
			context,
			instructor,
			instructor.getName(DepartmentalInstructor.sNameFormatLastInitial) + ": " + MESSAGES.noRole(),
			Source.SIMPLE_EDIT, 
			Operation.DELETE,
			null,
			instructor.getDepartment());
}
 
Example 7
Source File: DaoSupportImpl.java    From zevencourse with GNU General Public License v3.0 5 votes vote down vote up
public void update(T entity) {
	Session session = getSession();
	Transaction transaction = session.beginTransaction();
	session.update(entity);
       session.flush();
       transaction.commit();

}
 
Example 8
Source File: LoginDaoImpl.java    From Spring-MVC-Blueprints with MIT License 5 votes vote down vote up
@Transactional
@Override
public void updateUserRole(HrmsLogin login) {
	Session session = this.sessionFactory.getCurrentSession();
	session.update(login);

}
 
Example 9
Source File: MenuDAOImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void updateMenu(SbiMenu hibMenu) throws EMFUserError {
	Session tmpSession = null;
	Transaction tx = null;
	try {
		tmpSession = getSession();
		tx = tmpSession.beginTransaction();
		this.updateSbiCommonInfo4Update(hibMenu);
		tmpSession.evict(hibMenu);
		tmpSession.update(hibMenu);

		tx.commit();
	} catch (HibernateException he) {
		logException(he);

		if (tx != null)
			tx.rollback();

		throw new EMFUserError(EMFErrorSeverity.ERROR, 100);

	} finally {

		if (tmpSession != null) {
			if (tmpSession.isOpen())
				tmpSession.close();
		}

	}
}
 
Example 10
Source File: UserDaoImpl.java    From Resource with GNU General Public License v3.0 5 votes vote down vote up
@Override
@Transactional(propagation = Propagation.REQUIRED)
public void updateEntity(User user)
{
    Session session = sessionFactory.getCurrentSession();
    session.update(user);
}
 
Example 11
Source File: DeployProcessCommand.java    From uflo with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public ProcessDefinition execute(Context context) {
	Session session=context.getSession();
	String key=process.getKey();
	if(!update && StringUtils.isNotEmpty(key)){
		int size=session.createCriteria(ProcessDefinition.class).add(Restrictions.eq("key", key)).list().size();
		if(size>0){
			throw new IllegalArgumentException("Process definition "+process.getName()+"'s key "+key+" is not the only one!");
		}
	}
	int newVersion=1;
	if(!update){
		List<ProcessDefinition> processes=session.createCriteria(ProcessDefinition.class).add(Restrictions.eq("name",process.getName())).addOrder(Order.desc("version")).list();
		if(processes.size()>0){
			newVersion=processes.get(0).getVersion()+1;
			process.setVersion(newVersion);
		}else{
			process.setVersion(newVersion);
		}
	}
	if(StringUtils.isEmpty(key)){
		key=process.getName()+"-"+newVersion;
		process.setKey(key);
	}
	if(update){
		session.update(process);
	}else{
		session.save(process);			
	}
	return process;
}
 
Example 12
Source File: SbiAccessibilityPreferencesDAOHibImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
public void updateUiSettings(String userId, String preferences) throws EMFUserError {
	Session aSession = null;
	Transaction tx = null;
	try {
		aSession = getSession();
		tx = aSession.beginTransaction();
		Query q = aSession.createQuery("FROM SbiUser as user where user.userId ='" + userId + "'");
		SbiUser user = (SbiUser) q.uniqueResult();

		Criteria criteria = aSession.createCriteria(SbiAccessibilityPreferences.class);

		criteria.createAlias("user", "u").add(Restrictions.eq("u.userId", userId));

		SbiAccessibilityPreferences ap = null;
		if (!criteria.list().isEmpty()) {
			ap = (SbiAccessibilityPreferences) criteria.list().get(0);
		}

		if (ap != null) {
			ap.setUser(user);
			ap.setPreferences(preferences);
			updateSbiCommonInfo4Update(ap);
			aSession.update(ap);
		}
		tx.commit();

	} catch (HibernateException he) {
		logger.error(he.getMessage(), he);
		if (tx != null)
			tx.rollback();
		throw new EMFUserError(EMFErrorSeverity.ERROR, 100);
	} finally {
		if (aSession != null) {
			if (aSession.isOpen())
				aSession.close();
		}
	}
}
 
Example 13
Source File: EnversDemo.java    From HibernateDemos with The Unlicense 5 votes vote down vote up
public void insertData() {
	final Session s = openSession();
	s.getTransaction().begin();
	
	final Project project = new Project();
	project.setName( "fooName" );
	project.setType( "fooType" );
	s.persist( project );
	
	final Project project2 = new Project();
	project2.setName( "barName" );
	project2.setType( "barType" );
	s.persist( project2 );
	
	s.getTransaction().commit();
	
	for (int i = 0; i < 5; i++) {
		s.getTransaction().begin();
		
		project.setName( "fooName" + i );
		s.update( project );
		
		s.getTransaction().commit();
	}
	
	s.getTransaction().begin();
	project.setType( "fooType1" );
	s.update( project );
	s.getTransaction().commit();
	
	s.close();
}
 
Example 14
Source File: ReportDAO.java    From document-management-system with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Update
 */
public static void update(Report rp) throws DatabaseException {
	log.debug("update({})", rp);
	String qs = "select rp.fileContent, rp.fileName, rp.fileMime from Report rp where rp.id=:id";
	Session session = null;
	Transaction tx = null;

	try {
		session = HibernateUtil.getSessionFactory().openSession();
		tx = session.beginTransaction();

		if (rp.getFileContent() == null || rp.getFileContent().length() == 0) {
			Query q = session.createQuery(qs);
			q.setParameter("id", rp.getId());
			Object[] data = (Object[]) q.setMaxResults(1).uniqueResult();
			rp.setFileContent((String) data[0]);
			rp.setFileName((String) data[1]);
			rp.setFileMime((String) data[2]);
		}

		session.update(rp);
		HibernateUtil.commit(tx);
	} catch (HibernateException e) {
		HibernateUtil.rollback(tx);
		throw new DatabaseException(e.getMessage(), e);
	} finally {
		HibernateUtil.close(session);
	}

	log.debug("update: void");
}
 
Example 15
Source File: TopicDaoImpl.java    From Spring-MVC-Blueprints with MIT License 5 votes vote down vote up
@Transactional
@Override
public void updateTopic(CfsTopic topic) {
	Session session = this.sessionFactory.getCurrentSession();
	session.update(topic);
	session.flush();

}
 
Example 16
Source File: InterceptorDynamicEntityTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
public void testIt() {
	// Test saving these dyna-proxies
	Session session = openSession();
	session.beginTransaction();
	Company company = ProxyHelper.newCompanyProxy();
	company.setName( "acme" );
	session.save( company );
	Customer customer = ProxyHelper.newCustomerProxy();
	customer.setName( "Steve" );
	customer.setCompany( company );
	session.save( customer );
	session.getTransaction().commit();
	session.close();

	assertNotNull( "company id not assigned", company.getId() );
	assertNotNull( "customer id not assigned", customer.getId() );

	// Test loading these dyna-proxies, along with flush processing
	session = openSession();
	session.beginTransaction();
	customer = ( Customer ) session.load( Customer.class, customer.getId() );
	assertFalse( "should-be-proxy was initialized", Hibernate.isInitialized( customer ) );

	customer.setName( "other" );
	session.flush();
	assertFalse( "should-be-proxy was initialized", Hibernate.isInitialized( customer.getCompany() ) );

	session.refresh( customer );
	assertEquals( "name not updated", "other", customer.getName() );
	assertEquals( "company association not correct", "acme", customer.getCompany().getName() );

	session.getTransaction().commit();
	session.close();

	// Test detached entity re-attachment with these dyna-proxies
	customer.setName( "Steve" );
	session = openSession();
	session.beginTransaction();
	session.update( customer );
	session.flush();
	session.refresh( customer );
	assertEquals( "name not updated", "Steve", customer.getName() );
	session.getTransaction().commit();
	session.close();

	// Test querying
	session = openSession();
	session.beginTransaction();
	int count = session.createQuery( "from Customer" ).list().size();
	assertEquals( "querying dynamic entity", 1, count );
	session.clear();
	count = session.createQuery( "from Person" ).list().size();
	assertEquals( "querying dynamic entity", 1, count );
	session.getTransaction().commit();
	session.close();

	// test deleteing
	session = openSession();
	session.beginTransaction();
	session.delete( company );
	session.delete( customer );
	session.getTransaction().commit();
	session.close();
}
 
Example 17
Source File: CollectionTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
public void testUpdateOrder() {
	Session s = openSession();
	Transaction t = s.beginTransaction();
	User u = new User( "gavin" );
	u.getSessionData().put( "foo", "foo value" );
	u.getSessionData().put( "bar", "bar value" );
	u.getEmailAddresses().add( new Email( "[email protected]" ) );
	u.getEmailAddresses().add( new Email( "[email protected]" ) );
	u.getEmailAddresses().add( new Email( "[email protected]" ) );
	u.getEmailAddresses().add( new Email( "[email protected]" ) );
	s.persist( u );
	t.commit();
	s.close();

	u.getSessionData().clear();
	u.getSessionData().put( "baz", "baz value" );
	u.getSessionData().put( "bar", "bar value" );
	u.getEmailAddresses().remove( 0 );
	u.getEmailAddresses().remove( 2 );

	s = openSession();
	t = s.beginTransaction();
	s.update( u );
	t.commit();
	s.close();

	u.getSessionData().clear();
	u.getEmailAddresses().add( 0, new Email( "[email protected]" ) );
	u.getEmailAddresses().add( new Email( "[email protected]" ) );

	s = openSession();
	t = s.beginTransaction();
	s.update( u );
	t.commit();
	s.close();

	s = openSession();
	t = s.beginTransaction();
	s.delete( u );
	t.commit();
	s.close();

}
 
Example 18
Source File: RaceDAO.java    From pikatimer with GNU General Public License v3.0 4 votes vote down vote up
public void updateSplit (Split sp) {
   Session s=HibernateUtil.getSessionFactory().getCurrentSession();
   s.beginTransaction(); 
   s.update(sp);
   s.getTransaction().commit();
}
 
Example 19
Source File: ObjParviewDAOHibImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Modify obj parview.
 *
 * @param aObjParview the a obj parview
 *
 * @throws EMFUserError the EMF user error
 *
 * @see it.eng.spagobi.behaviouralmodel.analyticaldriver.dao.IObjParviewDAO#modifyObjParview(it.eng.spagobi.behaviouralmodel.analyticaldriver.bo.ObjParview)
 */
@Override
public void modifyObjParview(ObjParview aObjParview) throws HibernateException {
	Session aSession = null;
	Transaction tx = null;
	try {
		aSession = getSession();
		tx = aSession.beginTransaction();
		// get the existing object
		String hql = "from SbiObjParview s where s.id = ? ";

		Query hqlQuery = aSession.createQuery(hql);
		hqlQuery.setInteger(0, aObjParview.getId().intValue());

		SbiObjParview sbiObjParview = (SbiObjParview) hqlQuery.uniqueResult();
		if (sbiObjParview == null) {
			SpagoBITracer.major(SpagoBIConstants.NAME_MODULE, this.getClass().getName(), "modifyObjParview",
					"the ObjParview relevant to BIObjectParameter with " + "id=" + aObjParview.getParId() + "  does not exist.");

		}
		// delete the existing object
		// aSession.delete(sbiObjParview);
		// create the new object

		SbiObjPar sbiObjPar = (SbiObjPar) aSession.load(SbiObjPar.class, aObjParview.getParId());
		SbiObjPar sbiObjParFather = (SbiObjPar) aSession.load(SbiObjPar.class, aObjParview.getParFatherId());
		if (sbiObjParFather == null) {
			SpagoBITracer.major(SpagoBIConstants.NAME_MODULE, this.getClass().getName(), "modifyObjParview",
					"the BIObjectParameter with " + " does not exist.");
		}

		sbiObjParview.setSbiObjPar(sbiObjPar);
		sbiObjParview.setSbiObjParFather(sbiObjParFather);
		sbiObjParview.setOperation(aObjParview.getOperation());
		sbiObjParview.setCompareValue(aObjParview.getCompareValue());
		sbiObjParview.setId(aObjParview.getId());
		sbiObjParview.setProg(aObjParview.getProg());
		sbiObjParview.setViewLabel(aObjParview.getViewLabel());

		// save new object
		updateSbiCommonInfo4Insert(sbiObjParview);
		aSession.update(sbiObjParview);
		tx.commit();
	} catch (HibernateException he) {
		logException(he);
		if (tx != null)
			tx.rollback();
		throw new HibernateException(he.getLocalizedMessage(), he);
	} finally {
		if (aSession != null) {
			if (aSession.isOpen())
				aSession.close();
		}
	}
	/*
	 * Criterion aCriterion = Expression.and( Expression.eq("id.sbiObjPar.objParId", aObjParuse.getObjParId()), Expression.eq("id.sbiParuse.useId",
	 * aObjParuse.getParuseId())); Criteria aCriteria = aSession.createCriteria(SbiObjParuse.class); aCriteria.add(aCriterion); SbiObjParuse sbiObjParuse =
	 * (SbiObjParuse) aCriteria.uniqueResult();
	 */
}
 
Example 20
Source File: HibernateLayer.java    From geomajas-project-server with GNU Affero General Public License v3.0 2 votes vote down vote up
/**
 * Update a feature object in the Hibernate session.
 *
 * @param feature feature object
 * @throws LayerException oops
 */
public void update(Object feature) throws LayerException {
	Session session = getSessionFactory().getCurrentSession();
	session.update(feature);
}