Transaction Interceptor CDI JPA JavaSE

913 views Asked by At

I made an interceptor transactions for my DAOs using CDI. However, the EntityManager that is injected into the DAO, is not the same used in the transaction interceptor. How can I do to use the same EntityManager?

DAO Class

public class GenericDAO<T, PK> {

    public final EntityManager manager;

    public GenericDAO(EntityManager manager) {
        this.manager = manager;
    }

    @Transactional
    public T getById(PK pk) {
        Object o = manager.find(getTypeClass(), (Serializable) pk);
        return (T) o;
    }
}

EntityManager Producer:

public class EntityManagerProducer implements Serializable {

    private static final long serialVersionUID = 1L;

    @Produces
    public EntityManager createEntityManager() {
        return Persistence.createEntityManagerFactory("bd").createEntityManager();
    }

    public void closeEntityManager(@Disposes EntityManager manager) {
        if (manager.isOpen()) {
            manager.close();
            System.out.println("CLOSE ENTITY MANAGER !!!!");
        }
    }
}

I see that it is created twice because the print on Method closeEntityManager is invoked twice.

1

There are 1 answers

1
Harald Wellmann On BEST ANSWER

Since your producer method has @Dependent scope, it will produce a new EntityManager instance for each injection point.

By the way, rather than rolling your own transactional interceptor, you might want to check out DeltaSpike (JPA and Data modules).