EJB @PersistenceContext EntityManager Throws NullPointerException
1.junit 测试时,无法使用依赖注入的方式,得到EntityManger
@PersistenceContext(unitName = "trust")
protected EntityManager em=factory.createEntityManager();
目前JBoss 4.2集成了的Tomcat版本为5.5,但Tomcat 6.0以后的版本中才支持使用注释,所以如果将本例中Servlet运行在JBoss 4.2中,并不能获得EntityManagerFactory对象;但在符合J2EE 5.0的服务器中,这样运行是可以的。
虽然在目前JBoss 4.2版本中不支持使用注释,但可以通过另一种方式来获得应用托管的EntityManager对象
解决方案:
1.-改为通过工厂来新建
private static EntityManagerFactory factory;
static{
factory=Persistence.createEntityManagerFactory("jpaUnit");
}
protected EntityManager em=factory.createEntityManager();
外文链接:http://stackoverflow.com/questions/20592925/ejb-persistencecontext-entitymanager-throws-nullpointerexception
http://stackoverflow.com/questions/6469751/testing-an-ejb-with-junit