Java Reference
In-Depth Information
@UserDatabase
private EntityManager em;
...
}
The class does not explicitly produce a persistence unit field, but the application has
a persistence.xml file that specifies a persistence unit. The class is annotated
javax.inject.Singleton to specify that the injector should instantiate it only
once.
The db.UserDatabaseEntityManager class also contains commented-out code
that uses create and close methods to generate and remove the producer field:
Click here to view code image
/* @PersistenceContext
private EntityManager em;
@Produces
@UserDatabase
public EntityManager create() {
return em;
} */
public void close(@Disposes @UserDatabase EntityManager em) {
em.close();
}
You can remove the comment indicators from this code and place them around the field
declaration to test how the methods work. The behavior of the application is the same with
either mechanism.
The advantage of producing the EntityManager in a separate class rather than simply
injecting it into an enterprise bean is that the object can easily be reused in a typesafe way.
Also, a more complex application can create multiple entity managers using multiple per-
sistence units, and this mechanism isolates this code for easy maintenance, as in the fol-
lowing example:
Click here to view code image
@Singleton
public class JPAResourceProducer {
@Produces
@PersistenceUnit(unitName="pu3")
@TestDatabase
EntityManagerFactory customerDatabasePersistenceUnit;
Search WWH ::




Custom Search