The JNDI providers work with almost no special configuration at all. The JPAContainerFactory has factory methods for creating various JNDI provider types. The only thing that you commonly need to do is to expose the EntityManager to a JNDI address. By default, the JNDI providers look for the EntityManager from "java:comp/env/persistence/em". This can be done with the following snippet in web.xml or with similar configuration with annotations.
<persistence-context-ref> <persistence-context-ref-name>
persistence/em </persistence-context-ref-name>
<persistence-unit-name>MYPU</persistence-unit-name> </persistence-context-ref>
The "MYPU" is the identifier of your persistence unit defined in your persistence.xml file.
If you choose to annotate your servlets (instead of using the web.xml file as described above), you can simply add the following annotation to your servlet.
@PersistenceContext(name="persistence/em",unitName="MYPU")
If you wish to use another address for the persistence context, you can define them with the setJndiAddresses() method.You can also define the location for the JTA UserTransaction, but that should be always accessible from "java:comp/UserTransaction" by the JEE6 specification.
21.5.3. Entity Providers as Enterprise Beans
Entity providers can be Enterprise JavaBeans (EJB). This may be useful if you use JPAContainer in a Java EE application server. In such case, you need to implement a custom entity provider that allows the server to inject the entity manager.
For example, if you need to use Java Transaction API (JTA) for JPA transactions, you can implement such entity provider as follows. Just extend a built-in entity provider of your choise and annotate the entity manager member as @PersistenceContext. Entity providers can be either stateless or stateful session beans. If you extend a caching entity provider, it has to be stateful.
@Stateless
@TransactionManagement
public class MyEntityProviderBean extends MutableLocalEntityProvider<MyEntity> {
@PersistenceContext private EntityManager em;
protected LocalEntityProviderBean() { super(MyEntity.class); setTransactionsHandledByProvider(false);
}
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED) protected void runInTransaction(Runnable operation) {
super.runInTransaction(operation);
}
@PostConstruct public void init() {
setEntityManager(em);
/*
*The entity manager is transaction-scoped, which means
*that the entities will be automatically detached when
*the transaction is closed. Therefore, we do not need