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 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With