So you’re getting started with your Java EE web project and you’re using JPA, annotations, dependency injection, all that good stuff. Except when you launch your awesome web app, your Glassfish 3 server spits out something like this:
description The server encountered an internal error () that prevented it from fulfilling this request.
exception
javax.servlet.ServletException: javax.ejb.CreateException: Could not create stateless EJB
root cause
javax.ejb.CreateException: Could not create stateless EJB
root cause
java.lang.IllegalStateException: Exception attempting to inject Env-Prop: org.example.EjbClass/emf@Field-Injectable Resource. Class name = org.example.EjbClass Field name=emf@java.lang.String@@@ into class org.example.EjbClass: Can not set javax.persistence.EntityManagerFactory field org.example.EjbClass.emf to com.sun.enterprise.container.common.impl.EntityManagerWrapper
root cause
com.sun.enterprise.container.common.spi.util.InjectionException: Exception attempting to inject Env-Prop: org.example.EjbClass/emf@Field-Injectable Resource. Class name = org.example.EjbClass Field name=emf@java.lang.String@@@ into class org.example.EjbClass: Can not set javax.persistence.EntityManagerFactory field org.example.EjbClass.emf to com.sun.enterprise.container.common.impl.EntityManagerWrapper
root cause
java.lang.IllegalArgumentException: Can not set javax.persistence.EntityManagerFactory field org.example.EjbClass.emf to com.sun.enterprise.container.common.impl.EntityManagerWrapper
If you’re reading the error message carefully, like my friend didn’t, you’ll notice that it’s complaining about trying to set an EntityManager instance on an EntityManagerFactory field.
Why, oh why, would it do this?
Because you’re using the @PersistenceContext annotation on the field, instead of @PersistenceUnit. Ouch.
I was a victim of this mistake today! Thanks for pointing me in the right direction!
Thanks.
Hey man, good article!
But why the hell tells us the oracle tutorial to set @PersistenceContext to the emf field as you can read here:
http://docs.oracle.com/cd/E19798-01/821-1841/bnbqy/index.html
Read the example about Application-Managed Entity Managers!
Apparently, the author of the documentation made the same mistake that inspired this blog post. ;)
In a nutshell, @PersistenceContext is for EntityManager instances, @PersistenceUnit is for EntityManagerFactory instances.
excellent.
Thanks so much. Still relevant in 2015!