Monday, April 22, 2013

Hibernate autocommit session + Transaction.

This feature is extremely dangerous If we are not aware of. For example:
Let's say I have a simple service method :
  @Transactional  
   public void addCompany(Company company) {  
       company.setName("Name_1");
       companyDAO.saveOrUpdate(company); 
       company.setName("Name_2");
   }  

companyDAO is using HibernateSupport to manage entities.
What do we expect the name of our company in the DB looks like ?
At first glimpse, one might just state : "Name_1" because we actually did not call DAO to save our entity.
However, that's might not be the case if autocommit feature of Hibernate session is ON (I think it is ON by default). Therefore:
companyDAO.saveOrUpdate(company); will attach company entity to current Hibernate session. And when transaction ends, Hibernate will try to commit session. As the result, name of target entity in DB is actually "Name_2". Suprise(or not) :) ! Transaction gives us great power, but great power comes great responsibility ;)

No comments:

Post a Comment