Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it necessary to make a rollback on a transaction in the catch-block?

Maybe a stupid question, but is it necessary to make a rollback on a transaction in the catch-block if the EntityManager.merge() throws an exception? Or does the exception itself mean that the merge won´t work so that next time I run commit the previous changes that throwed the exception won´t apply?

Example:

public void setPerson(Person person) {
EntityManagerFactory emf =   Persistence.createEntityManagerFactory("MyLib");
     EntityManager em = emf.createEntityManager();
     try {            
         if(!em.getTransaction().isActive()){
            em.getTransaction().begin();
         }
         em.merge(person);
         em.getTransaction().commit();
         emf.getCache().evict(Person.class); // clear Person cache
     } catch (Exception ex){
         em.getTransaction().rollback(); // Is this necessary?   
     } finally {
         em.close();
     }
}
like image 611
Rox Avatar asked Oct 08 '22 01:10

Rox


1 Answers

The answer depends on the details of em.merge(person) method and the implementation of your database driver.

If that method only performs one update statement, then the rollback is superfluous. If however it may run multiple updates, then it's not that clear.

I personally would keep it there

If the rollback is removed and your merge method errors our after some updates are done but others are not, then closing a database connection without explicit commit or rollback will either commit or rollback the transaction, depending on the driver implementation. According to the javadoc for java.sql.Connection, the behaviour depends on the implementation. Hence you may end up committing partial updates if you do not rollback yourself on error.

like image 137
Aleks G Avatar answered Oct 18 '22 11:10

Aleks G