Skip to main content

LOTD #22: How to inject JPA resources ? - PersistenceUnit vs PersistenceContext

Posted by arungupta on August 19, 2009 at 3:39 PM PDT



Java Persistence API defines a standard object/relational mapping using
POJOs. In JPA, a persistence
unit
is described using "persistence.xml", bundled with
the web application, injected into your web application and then POJOs
are used to access all the information from the underlying persistence
mechanism such as a database.



JPA can injected into your application couple of different ways as
shown below:


style="text-align: left; background-color: rgb(204, 204, 255); width: 100%;"
cellpadding="2" cellspacing="2">
@PersistenceUnit

EntityManagerFactory emf;



and


style="text-align: left; background-color: rgb(204, 204, 255); width: 100%;"
cellpadding="2" cellspacing="2">
@PersistenceContext

EntityManager manager;



Which one is preferred, why, and pros/cons are very clearly explained
in (slightly old but very relevant) href="http://weblogs.java.net/blog/ss141213/archive/2005/12/dont_use_persis_1.html">this
blog. It also discusses a JNDI approach.



In case you are interested in the summary:

  • Use "@PersistenceUnit EntityManagerFactory" for Servlets
    because of thread safety
  • Use "@PersistenceContext EntityManager" in EJBs for
    simpler/cleaner code

Read other JPA
related entries
.

All previous entries in this series are archived at href="http://blogs.sun.com/arungupta/tag/lotd">LOTD.




Technorati: lotd
glassfish
jpa href="http://technorati.com/tags/javaee">javaee href="http://technorati.com/tags/persistence">persistence

Related Topics >>