In the
Hibernate we will very likely never see this idiom in business code in a normal application; fatal (system) exceptions
should always be
caught at the "top". In other words, the code that
executes entity manager calls (in the persistence layer) and the code that handles
RuntimeException (and usually can only clean up and exit) are in different layers. This can be a challenge to design yourself and you should use
J2EE/EJB container services whenever they are available.
If an JPA persistence layer runs in a non-managed environment, database connections are usually handled by Hibernate's pooling mechanism behind the scenes. The common entity manager and transaction handling idiom looks like this:
// Non-managed environment idiom
EntityManager em = emf.createEntityManager();
EntityTransaction tx = null;
try {
tx = em.getTransaction();
tx.begin();
// do some work
...
tx.commit();
}
catch (RuntimeException e)
{
if ( tx != null && tx.isActive() ) tx.rollback();
throw e; // or display error message
}
finally
{
em.close();
}
You don't have to flush() the EntityManager explicitly - the call to commit() automatically triggers the synchronization.
A call to close() marks the end of an EntityManager. The main implication of close() is the release of resources - make sure you always close and never outside of guaranteed finally block.