Hi,
I have a question about the safety of an EJB 3.0 design pattern that I've evolved during the development of a project. It seems naive to me now in retrospect, but could someone please comment in more detail about its safety?
I have a stateless EJB that obtains an EntityManager via the following injection:
@PersistenceContext(unitName="pid") private EntityManager manager;
@PostConstruct public void init() { muHelper = new MatchUnitHelper(manager); jobHelper = new JobHelper(manager); // ... etc }
If the EntityManager throws an exception (including any SQLException), you should immediately rollback the database transaction, call EntityManager.close() (if createEntityManager() has been called) and discard the EntityManager instance. Certain methods of EntityManager will not leave the persistence context in a consistent state. No exception thrown by an entity manager can be treated as recoverable. Ensure that the EntityManager will be closed by calling close() in a finally block. Note that a container managed entity manager will do that for you. You just have to let the RuntimeException propagate up to the container.