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();
}
}
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
rollbackis superfluous. If however it may run multiple updates, then it’s not that clear.I personally would keep it there
If the
rollbackis removed and yourmergemethod errors our after some updates are done but others are not, then closing a database connection without explicitcommitorrollbackwill either commit or rollback the transaction, depending on the driver implementation. According to the javadoc forjava.sql.Connection, the behaviour depends on the implementation. Hence you may end up committing partial updates if you do notrollbackyourself on error.