-->@PersistenceContext(unitName="ejbjpa-hotel", type=PersistenceContextType.TRANSACTION)
private EntityManager em;
Extended Scope
persistence context may see multiple Tx
only relevant for Stateful EJBs
@PersistenceContext(unitName="ejbjpa-hotel", type=PersistenceContextType.EXTENDED)
private EntityManager em;
@PersistenceUnit
Injected with EntityManagerFactory
May be used to implement BEAN-managed transactions
Persistence unit (EntityManagerFactory) being injected from a JTA-managed source
BEAN-managed transactions means JTA transaction controlled thru injected UserTransaction
Method programmatically controlling scope of JTA transaction
em.joinTransaction() called on EntityManager created outside scope of JTA transaction
@Singleton
@Startup
@TransactionManagement(TransactionManagementType.BEAN)
public class HotelInitEJB implements HotelInitRemote {
@PersistenceUnit(unitName="ejbjpa-hotel")
private EntityManagerFactory emf;
@Resource
private UserTransaction tx;
@Override
public void businessMethod() {
EntityManager em=emf.createEntityManager();
HotelDAO dao = new JPAHotelDAO();
((JPAHotelDAO)dao).setEntityManager(em);
tx.begin();
em.joinTransaction(); //tells the EM to join the JTA Tx
...
tx.commit();
em.close();
}
}
Newer technique -- JavaEE's answer to Spring Configuration
package ejava.examples.jndidemo;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.RetentionPolicy.*;
import static java.lang.annotation.ElementType.*;
import javax.inject.Qualifier;
@Qualifier
@Retention(RUNTIME)
@Target({METHOD, FIELD, PARAMETER, TYPE})
public @interface JndiDemo {
}
Define producer of Persistence Context
import javax.enterprise.inject.Produces;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
public class SchedulerResources {
@PersistenceContext(unitName="jndidemo")
@Produces
@JndiDemo
public EntityManager em;
@Stateless
public class TrainSchedulerEJB
extends SchedulerBase implements TrainSchedulerRemote {
@Inject @JndiDemo
private EntityManager em;