Do I need to roll back a transaction in a catch block?

Maybe a stupid question, but is it necessary to roll back a transaction in a catch-block if EntityManager.merge () throws an exception? Or does the exception itself mean that the merge will not work, so the next time I started committing previous changes that selected the exception will not 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();
     }
}
+5
source share
1 answer

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

If this method performs only one update action, then it rollbackis redundant. If, however, it can run several updates, then this is not so clear.

I personally would leave him there

rollback , merge , , , commit rollback , , . javadoc java.sql.Connection, . , , rollback .

+4

All Articles