Injecting entity manager into managed bean - jsf-2

It is possible to inject entity manager (or its factory) into jsf managed bean using #PersistenceContext (or #PersistenceUnit)?
I Tried it but nothing, I obtain a NullPointerException.

Yes it is possible. This is the syntax.
#PersistenceContext
EntityManager em;
You need to have a persistence.xml in your project. Btw: I'm running Glassfish 3.
After this you can then use methods like em.createNamedQuery.
Also remember the injection takes place after the constructor so if your trying to do database functions in the constructor this will not work. You will have to add the #PostConstruct annotation to a method. This is probably the problem your having.

Related

JSF 2 ManagedProperty is null

I know there are loads of questions on SO regarding this exact issue, but I couldn't find a solution to my problem. I'm trying to use a #ManagedProperty in JSF 2. I used the example from this page, but mine's not working:
#ManagedProperty("#{userSession}")
private UserSession userSession;
public void setUserSession(UserSession userSession) {
this.userSession = userSession;
}
Both the parent bean and the bean injected are session scoped. Both beans have the #ManagedBean attribute. No faces-config.xml declarations, no EJBs, no use of Spring. One thing I noticed from that example is that both the bean classes implement Serializable. Mine do not, and I'm not sure if that is making the difference.
When I use this code, I get a NullPointerException when I try to operate on userSession. However, I know a session exists, because when I use #BalusC's findBean convenience method, it works. One thing with this though, is that my code only works if I call userSession = findBean("userSession") inside the same method where I'm "doing stuff". If I initialize userSession in the bean's constructor, I get another NPE. Any ideas?

How to access a local interfaces from one project into another within the same ear project

I have a web project that has FacesValidator, this validator needs to access an EJB service to verify if a record exists. Unfortunately, I cannot inject my enterprise beans since the validator is not a managed-bean, so I'm trying to access it via InitialContext. I've tried different combination from http://docs.oracle.com/javaee/6/tutorial/doc/gipjf.html but failed.
What works is this format:
java:global/myProject-ear-1.0.0/myProject/MyService!com.czetsuya.myProject.service.membership.MyService,
My question is can it be simplify? Seems too long.
Thanks,
czetsuya
Look at the server logs. A bit decent EJB container (at least, Glassfish 3 and JBoss 6/7 do), logs all available JNDI names of the EJB during EJB deployment step. Provided that the validator is properly been put in the WAR and the EJB has a #Local interface, then the shortest JNDI name would be the java:app one which should in your case have been java:app/myProject/MyService.
A completely different alternative is to just make the validator a JSF or CDI managed bean instead, so that you can just use the #EJB annotation.
#ManagedBean // Or #Named.
#ApplicationScoped // Provided that the instance doesn't have any state.
public class MyValidator implements Validator {
#EJB
private MyService myService;
// ...
}
and reference it by binding instead of validatorId:
<f:validator binding="#{myValidator}" />
Note that from JSF 2.2 on, you should be able to inject #EJB in a #FacesValidator (and #FacesConverter).
See also:
How to inject in #FacesValidator with #EJB, #PersistenceContext, #Inject, #Autowired

Why does the #PostConstruct method not get called using BeanManager.getReference() to obtain an instance?

We are currently moving from JSF-ManagedBeans to CDI. Unfortunately we have made excessive use of the EL-Resolver in the past in order to gain static access to session scoped beans managed by JSF.
Since CDI dependency injection is not available everywhere I rewrote the existing static lookup to make use of the BeanManager (Using SEAM-Solder extending BeanManagerAware).
Iterator<Bean<?>> iterator = beans.iterator();
Bean<T> bean = (Bean<T>) iterator.next(); // possible NPE, I know :)
CreationalContext<T> creationalContext = beanManager.createCreationalContext(bean);
T contextual = (T) beanManager.getReference(bean, type, creationalContext);
return contextual;
The code works and returns a container managed instance of the desired bean. BUT: the methods annotated with #PostConstruct do not get called using getReference(). Perhaps you guys know how to do it. Couldn't find anything googling the issue :-/
Best regards!
You should be using Application#evaluateExpressionGet() for this. Not only for CDI beans, but actually also for JSF beans you previously had.
FacesContext context = FacesContext.getCurrentInstance();
Bean bean = (Bean) context.getApplication().evaluateExpressionGet(context, "#{beanName}", Bean.class);
// ...
Much cleaner, however, is to just use CDI's #Inject or JSF's #ManagedProperty instead.
See also:
Get JSF managed bean by name in any Servlet related class

Question about multi-threading and EntityManager

I have been developing my web-app using JPA 2.0 implementation EclipseLink 2.2.0. I finally got around to running multi-threaded code and I got this exception:
java.lang.IllegalStateException: Attempting to execute an operation on a closed EntityManager.
The objects that have all the javax.persistence calls in my application are defined as application scoped, like this:
#Model
#ApplicationScoped
public class LocationControl implements Serializable {
#PersistenceContext private EntityManager em;
#Resource private UserTransaction utx;
// etc
And of course all the managed beans (usually RequestScoped or ConversationScoped) that want to access the data base do so like this:
#Inject private LocationControl lc;
So my question is this: Did I get that Exception through the use of #ApplicationScoped DAO? I had thought that it would be more efficient that way, since the container would not have to be continually re-creating this object on every request if it did not have a scope, and the DAO has no state of its own. However if the EntityManager and UserTransaction object have to be separate instances for each user, then that would be a problem.
Alternatively, I could use syncrhonized on the DAO methods, but I think that would cause thread lockups in the container (GlassFish).
Any advice appreciated.
#Model annotation was originally created to annotate request scoped beans, here is how it's defined:
#Named
#RequestScoped
#Stereotype
#Target({TYPE, METHOD, FIELD})
#Retention(RUNTIME)
public #interface Model {}
You can of course override '#RequestScoped' with another annotation but '#ApplicationScoped' it's not a good choice as everyone in the application would modify the state of the same injected EntityManager. I think it would be best to leave it #RequestScoped in most cases, sometimes, for example for a login/logout data bean '#SessionScoped' could be an option but I cannot see a scenario for '#ApplicationScoped' dao.
If you don't want to use #Model at all and you use full Java EE container, then the stateless EJB ,as BalusC said, would be a great option for Dao too.

Is there any Spring #Required annotation equivalent in EJB 3.0?

Is there any equivalent annotation in EJB for #Required (Spring)? I do dependency injection using setters and I want to be sure that resource was injected (almost no probability of NullPointerException ;)). In Spring it is easy:
#Required
public void setProperty(Property p) {
this.property = p;
}
Is there any way to do such a validation in EJB? (Maybe some other solution than annotatations). Thanks
In ejb injection is done via #EJB and #Resource (as stated above).
If the bean for the given (or auto-generated) name doesn't exist you get an error from the container (in many cases this happens at deployment time).
The only way to (maybe) get a nullpointer exception inside a ejb bean is if you try to access an injected object in the default constructor. By spec injection happens after the constructor and before the #PostConstruct lifecycle is called.

Resources