Common lib for EntityManager CDI

137 Views Asked by At

I have a common generic DAO in common lib. I want in each module which uses this DAO to initialize with its own persistence UNIT

public abstract class GenericDao implements IGenericDao {

@PersistenceContext(unitName = "XXXX")
private EntityManager entityManager;

and in other module

public class CarDao extends GenericDao{

I have lot of projects are using this generic DAO but each project have its own persistence unit.

Persitence unit are differents following the project where is used the common library

The point is i could not use POO with abstract getEntityManager injected in each micro servicies because in common project we have a history DAO common for all microservicies and for each one i have to retrieve the entityManager injected from the microservice

Am i doing wrong or well? and how set th epersistence unit in each project ? (each project have lot fo DAO and i don't want repet each time CRUD methods)

2

There are 2 best solutions below

5
Gab On
@PersistenceContext(unitName = "XXXX")
private EntityManager entityManager;

This should be done in each concrete class, the abstract one should implement the concrete operation using

getEntityManager().doSomething(entity)

the getter getEntityManager() being abstract.

Imho this is a design smell, EntityManager is already an abstraction and you have nothing to gain encapsulating it.

[edit]

Regarding the "factory" approach, the way in CDI to dynamically inject resources is using producer methods.

You can so create a method returning an EntityManager instance that will dynamically resolve the EntityManagerFactory according to the persistence unit name (see an example here).

Note that this is a very bad idea as the entityManager scope is usually bound to the transaction one, letting the container inject you the entityManager instance guarantee that the scope will be correctly handled (by the container). The only viable configuration with this approach is when you want an "application managed" entityManager

NB: note that the given example will instantiate a new EntityManageFactory instance for each injection which can be really catastrophic according to the way you use it (the EntityManageFactory should be created once for all the application)

be sure to be aware of EntityManager lifecycle before going further.

0
cyril On

Thank you guy for your advices in fact i was totally stupid in my genericDao i simply put

public abstract class GenericDao implements IGenericDao {


@PersistenceContext
private EntityManager entityManager; 

As we have only one PersistentUnit it will be automatically injected....

was so easy !

then i can use @PersistentContext in all DAOs or simply and best call getEntityManager from their parent IGenericDao