Thursday, May 24, 2007

Java EE5 Persistence Annotations for Web Applications

I am taking the time to create some cliff notes from a wonderful presentation at JavaOne TS-4593 "Guidelines, Tips, and Tricks for Using Java EE5 from Java Blueprints" (Inderjeet Singh, Marina Vatkina, and an article in JavaOne Today by Rick Palkovic. When the technical sessions are released to the general public, it would be a good read for any Java EE5 developer.

The problem has to do with thread safety on web applications. If you are using servlets, or a technology based on servlets like JSF, you must consider thread safety for persistence. A common injection is to use the container managed persistence context. This usually takes the following form

private EntityManager em;

The problem is this is NOT thread safe if used in a servlet. A servlet processes many requests and the container handles many requests. Even if you use an injection to get a UserTransaction, it lulls the programmer into a false sense of safety.

In their talk, they mentioned four methods to ensure thread safety on servlet based technologies
  • Use a request-scoped bean Java Server Faces. The life of the bean is a single transaction.
  • Use class level annotations with JNDI lookups
  • Use a @Resource annotation
  • Use the "old style" JNDI InitialContext lookup method
Here is an example of the "old-style" method:

public EntityManager getEntityManager() throws NamingException {
Context ic = new InitialContext();
return (EntityManager) ic.lookup("java:comp/env/EM");
Another alternative is to use the @PersistenceUnit annotation to get an EntityManagerFactory. The EntityManagerFactory is a thread-safe object. From the factory we create the EntityManager. This is also thread-safe since it creates a new EntityManager per call.

private EntityManagerFactory emf;

public EntityManager getEntityManager() {
return emf.createEntityManager();
These methods should help the developer maintain thread-safety.


Popular Posts