【发布时间】:2014-11-24 05:10:32
【问题描述】:
我正在使用 Jboss 提供的 JPA 库启动基于 struts2 的应用程序。 我已经在standalone.xml 中配置了数据源我可以从jboss 管理控制台看到 数据源已创建。并读取和处理 presistence.xml 文件。 但是,如果我检查 Action Class 中的 EntityManager 实例。它总是说 null。
这是我的 persistence.xml 和 Action 类 sn-p
<?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 动作类:
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;
}
}
【问题讨论】:
-
一些建议,因为我不知道确切的答案。您使用的是容器还是 bean 管理的持久性?如果是 CMT,那么您是否尝试过注入 entityManagerFactory 而不是 entityManager?
-
我没有使用 EJB。它适用于 Web 组件吗?
-
是的,确实如此。就像最初的建议一样,尝试注入 entityManagerFactory 而不是 entityManager。你可以谷歌了解如何做到这一点。如果您得到不同的答案,请先尝试他们的方法,因为我不太确定 entityManagerFactory 的附加值。
-
尝试注入 EMF 但仍然是同样的问题。这与 struts2 的名气有关..因为我写了简单的 servlet 并尝试注入 EM,它工作正常。如果我通过 strut2 调度程序或其他东西,它不起作用..
标签: java jpa struts2 jboss7.x cdi