0

Example :

import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.enterprise.context.RequestScoped;
import javax.enterprise.inject.Produces;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

@Stateless
@TransactionAttribute(TransactionAttributeType.SUPPORTS)
public class EntityManagerProducer
{
    @PersistenceContext
    private EntityManager entityManager;

    @Produces
    @RequestScoped
    public EntityManager getEntityManager() {
        return entityManager;
    }
}

The EntityManager can now be injected into other EJBs. For example,

@Stateless
@DeclareRoles(value={"ROLE_ADMIN", "ROLE_USER"})
@RolesAllowed(value={"ROLE_ADMIN"})
public class ZoneBean implements ZoneBeanRemote
{
    @Inject
    private EntityManager entityManager;

    //... This is a remote EJB.
}

Can this EntityManager safely be injected into a Stateful session bean like as follows?

@Stateful
@DeclareRoles(value={"ROLE_ADMIN", "ROLE_USER"})
@RolesAllowed(value={"ROLE_ADMIN"})
public class ZoneBean implements ZoneBeanRemote
{
    @Inject
    private EntityManager entityManager;

    //...
}

Another thing : is it necessary to take care of transactions here like closing of EntityManager at certain time?

Even, is the annotation @TransactionAttribute above the EntityManagerProducer EJB needed in this case or this is just a flaw and needs to be reconsidered (I assume, since EJBs use container-managed transactions, this should not be needed)?

What is the general convention of exposing an EntityManager as a CDI bean, if this approach does not suit?

I'm at present, working with GlassFish Server 4.1.

Tiny
  • 27,221
  • 105
  • 339
  • 599
  • What's the point of using @Inject in this case? For EJB, you should use `@PersictenceContext EntityManager em;` injection in any bean that needs it. – Gas Oct 20 '14 at 19:12
  • That point is not known to me. Hence, the question :) – Tiny Oct 20 '14 at 19:25

0 Answers0