Miles to go …

August 18, 2009

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

Filed under: glassfish, lotd — Tags: , , , , — arungupta @ 3:00 am

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:

@PersistenceUnit
EntityManagerFactory emf;

and

@PersistenceContext
EntityManager manager;

Which one is preferred, why, and pros/cons are very clearly explained in (slightly old but very relevant) 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 LOTD.

Technorati: lotd glassfish jpa javaee persistence

Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • DZone
  • StumbleUpon
  • Technorati
  • Twitter
  • Slashdot
Related posts:
  1. LOTD #3: Rails 2.2 going multi-threaded
  2. LOTD #13: Warbling with RMagick on GlassFish
  3. TOTD #109: How to convert a JSF managed bean to JSR 299 bean (Web Beans) ?
  4. LOTD #2: Phobos – MVC framework based on JavaScript
  5. LOTD #6: Rails Deployment on GlassFish in 4 steps and 15 minutes

1 Comment »

  1. Arun,

    Maybe a tip for a follow-up TOTD: how to combine OSGi and JPA in GlassFish v3?
    Example:
    Bundle A is a WAB with a PU and a class Foo, Bundle B contains class Bar extends Foo. How can B persist instances of Bar using JPA? (the PU in Bundle A doesn’t know how to persist class BAR).
    I can come up with a number of solutions that all have drawbacks.

    - Johan

    Comment by Johan Vos — August 18, 2009 @ 5:19 am

RSS feed for comments on this post. TrackBack URL

Leave a comment

Powered by WordPress