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)
This should be done in each concrete class, the abstract one should implement the concrete operation using
the getter
getEntityManager()being abstract.Imho this is a design smell,
EntityManageris 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
EntityManagerinstance that will dynamically resolve theEntityManagerFactoryaccording to the persistence unit name (see an example here).Note that this is a very bad idea as the
entityManagerscope is usually bound to the transaction one, letting the container inject you theentityManagerinstance 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"entityManagerNB: note that the given example will instantiate a new
EntityManageFactoryinstance for each injection which can be really catastrophic according to the way you use it (theEntityManageFactoryshould be created once for all the application)be sure to be aware of EntityManager lifecycle before going further.