问题
I have an EAR application with an EJB module, that contains one persistence unit and many EJBs (as service and DAO layer).
@Stateless
public class BranchDAO {
@PersistenceContext
private EntityManager entityManager;
}
But DAOs as Stateless beans are not recommended. So I create this annotation using CDI:
@Dependent
@Stereotype
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface DAO {
}
After my DAO is changed to not use @Stateless
:
@DAO
public class BranchDAO {
@PersistenceContext
private EntityManager entityManager;
}
But the Glassfish doesn't bring up the entity manager when the application starts. And when I call the DAO, the entity manager is in an illegal state.
java.lang.IllegalStateException: Unable to retrieve EntityManagerFactory for unitName null
This error only occurs in Glassfish 3, but not in JBoss AS 6. Using JBoss AS 6 I can see the Hibernate logs in startup (but I don't see them with Glassfish).
As a temporary solution I created an Stateless bean with the content below. It's not beautiful solution, but works fine in Glassfish.
@Stateless
@Startup
public class AutoStartEntityManager {
@PersistenceContext
private EntityManager entityManager;
}
So, how I can force Glassfish to bring up EntityManager when I'm not using @Stateless
in my DAO?
回答1:
Try specifying explicitly the unitName:
@PersistenceContext(unitName="yourJPAUnitName")
private EntityManager manager;
(A sidenote - are you sure you need the DAO in dependent scope? Shouldn't it be singleton?)
来源:https://stackoverflow.com/questions/4877286/glassfish-doesnt-bring-up-entitymanager-if-dao-is-not-stateless