java - Inject PersistenceContext with CDI -
currently, i'm using persistencecontext inject entitymanager. em injected perfectly.
@stateless public statelesssessionbean implements statelesssessionbeanlocal { @persistencecontext(unitname = "mypersistenceunit") private entitymanager em; @override public collection<myobject> getallobjects(){ criteriabuilder cb = em.getcriteriabuilder(); criteriqquery<myobject> query = cb.createquery(myobject.class); query.from(myobject); return em.createquery(query).getresultlist(); } }
now try decorate bean, , em doesn't injected. nullpointerexception.
@decorator public statelesssessionbeandecorator implements statelesssessionbeanlocal { @inject @delegate @any statelesssessionbeanlocal sb @override public collection<myobject> getallobjects(){ system.out.println("decorated method!"); return sb.getallobjects(); } }
i know ejb , cdi 2 different managers, 1 doesn't know other. i'm expecting @persistencecontext ejb injection point, while @inject cdi one. should solve , entitymanager injected should?
the best practice persistence context , cdi make them cdi bean avoid these kind of issue.
public class myproducers { @produces @persistencecontext(unitname = "mypersistenceunit") private entitymanager em; }
after you'll able inject entitymanager
in cdi way. taking ejb it'll :
@stateless public statelesssessionbean implements statelesssessionbeanlocal { @inject private entitymanager em; @override public collection<myobject> getallobjects(){ criteriabuilder cb = em.getcriteriabuilder(); criteriqquery<myobject> query = cb.createquery(myobject.class); query.from(myobject); return em.createquery(query).getresultlist(); } }
this way, you'll able decorate cdi bean no issue.
if have multiple entitymanagers
can use cdi qualifiers distinguish them
Comments
Post a Comment