Wednesday, January 05, 2011

@PersistenceUnit vs @PersistenceContext in Servlets

Duke, the Java Mascot, in the waving pose. Duk...Image via Wikipedia
Someone posted a comment that they could not use @PersistenceContext in a servlet based on a previous post Persistence Unit or Persistence Context?. Normally I would just chock it up to someone doing something wrong, and try to help them fix it. However, I thought it would be a good teaching moment. I am usually found in the JSF world,  and don't use servlets directly much anymore. That is until recently.

I have attached a NetBeans 6.9.1 Java EE 6 project called which shows that you can use both @PersistenceUnit and @PersistenceContext in a servlet. In fact this particular servlet uses both. The application uses the default JavaDB database in GlassFish.

Note: Just because both work, does not mean it is always the best course of action. In your enterprise applications you should be using @PersistenceUnit because it is thread safe. (Thanks @alexismp for reminding me of that, and sending me Sahoo's article link.). Sahoo wrote a good article on this with a good explanation: Don't use @PersistenceContext in a web app....

It is a simple example using multiple Java EE 6 technologies. You should get this result if you run it in NetBeans 6.9.1

Enhanced by Zemanta