我正在使用 Jboss 提供的 JPA 库启动基于 struts2 的应用程序。 我已经在standalone.xml中配置了数据源,我可以从jboss管理控制台看到 数据源已创建。读取并处理 presistence.xml 文件。 但是如果我检查 Action 类中的 EntityManager 实例。它总是说 null。
这是我的 persistence.xml 和 Action 类片段
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="primary">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>java:jboss/datasources/mysqlDS</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<!-- Properties for Hibernate -->
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.hbm2ddl.auto" value="update" />
<property name="hibernate.use_sql_comments" value="true" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
</properties>
</persistence-unit>
</persistence>
Struts2 Action 类:
public class RegistrationAction extends ActionSupport implements SessionAware,Preparable ,ModelDriven{
/**
*
*/
private static final long serialVersionUID = 1L;
@PersistenceContext(unitName="primary")
private EntityManager em;
@Override
public Object getModel() {
// TODO Auto-generated method stub
return null;
}
@Override
public void prepare() throws Exception {
if(em==null)
System.out.println(" EM is null still..");
//even Persistence.createEntityManagerFactory("primary"); returning NULL
}
@Override
public void setSession(Map<String, Object> arg0) {
// TODO Auto-generated method stub
}
public EntityManager getEm() {
return em;
}
public void setEm(EntityManager em) {
this.em = em;
}
}
最佳答案
操作由Struts 容器管理。
EntityManager 由CDI 容器管理。您可以将其注入(inject)到 CDI 托管对象(EJB 容器中的 EJB、CDI 托管 bean、servlet、ecc...)中,但不能注入(inject)到操作中。
您需要使用Struts2-CDI-Plugin或执行查找来获取它。顺便说一句,您甚至不应该将其注入(inject)到 Actions 中,最好使用业务组件(例如 EJB)并对其执行查找。
如果不使用 CDI 插件(例如因为使用 Spring 插件),CDIUtil.java Rob Veldpaus 的作品非常适合此目的。
示例 EJB:
@Stateless
public class MyEjb{
@PersistenceContext(unitName="primary")
EntityManager em;
public Foo find(long id){
return em.find(Foo.class, id);
}
}
示例操作:
public class RegistrationAction extends ActionSupport
implements SessionAware,Preparable ,ModelDriven {
public String execute(){
MyEjb ejb = new CdiUtil().lookup(MyEjb.class);
System.out.println(ejb.find(1L));
return SUCCESS;
}
/* your other stuff here */
}
关于java - JPA EntityManager 未在 struts2 和 JBOSS 7.1 中初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27098228/