I have looked though a lot of the tutorials and documentation looking for
the *right* way perform an operation with JPA in regards to handling
exceptions and closing EntityManagers. here is my first stab an a
quintessential JPA operation.
public void performOperation(){
EntityManager entityManager = managerFactory.createEntityManager();
EntityTransaction tx = null;
try{
tx = entityManager.getTransaction();
tx.begin();
//perform business operations. thrown exceptions cause rollback.
tx.commit();
}catch(Exception e){
//log error, etc.
}finally{
if (tx != null && tx.isActive()){
tx.rollback();
}
entityManager.close();
}
}
Some notes. There is exactly one tx.commit() and exactly one tx.rollback().
this is to insure that they are called when intended. I am only catching
Exceptions and not Throwables. Im not a big fan of catching Throwable since
you can swallow really critical errors, like OutOfMemmoryError. Some
improvements that come to mind, though I am not sure about, are that the
tx.rollback() might throw an exception and prevent the entityManager from
being closed. I like having the rollback in the finally though.
Does any one have any ideas about this? or know of a really good example. I
would love to see them.
-Lucas