使用带有transaction-type =" JTA"的@PersistenceContext,DAO中的EntityManager为空。

时间:2018-06-04 13:13:19

标签: jpa ejb eclipselink ejb-3.0 ejb-3.1

我面临着在DAO课程中注入实体经理的问题,我搜索了很多解决方案,但无法解决这个问题。

我有EJB Bean Class

@Stateless(name = "MyBean", mappedName = "MyBean")
@Remote(MYRemoteBeanI.class)
public class MyBeanImpl implements MYRemoteBeanI {

@EJB
MyDAO dao; // This DAO gets injected. But entity manager inside this DAO is null

}

DAO课程

@Stateless
public class MyDAO {

//This is not injecting, it will be always null
@PersistenceContext(unitName="MyPersistenceUnit")
private EntityManager entityManager; 

}

Persistence.xml如下

<persistence-unit name="MyPersistenceUnit" transaction-type="JTA">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<jta-data-source>myDataSource</jta-data-source>
<mapping-file>META-INF/orm.xml</mapping-file>
<!-- Some managed classes -->
<!-- Some properties -->
</persistence-unit>
</persistence>

请帮助我解决这个问题。我是EJB世界的新手!

1 个答案:

答案 0 :(得分:0)

似乎没有从Persistence.xml读取您的 persistence-unit 。 xml位于哪里?

这是Jboss 7 / Wildfly中连接到Oracle DB的工作示例。

@Stateless
public class MyServiceImpl implements MyService {
    @EJB(name = "myDAO")
    private MyDAO segmentDTO;
}

@Local
public interface MyDAO {

}

@Stateless
public class MyDAOImpl implements MyDAO {
    @PersistenceContext(unitName = "exampleEM")
    protected EntityManager entityManager;
}

resources / META-INF / persistence.xml

<persistence>
    <persistence-unit name="exampleEM" transaction-type="JTA">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>

        <jta-data-source>java:jboss/datasources/ExampleDS</jta-data-source>
        <!-- your entities -->

        <properties>
            <property name="hibernate.connection.autocommit" value="false" />
            <property name="hibernate.dialect" value="org.hibernate.dialect.OracleDialect" />
            <property name="hibernate.show_sql" value="false" />
            <property name="hibernate.format_sql" value="false" />
            <property name="hibernate.use_sql_comments" value="false" />
            <property name="hibernate.id.new_generator_mappings" value="true"/>
            <property name="hibernate.hbm2ddl.auto" value="create-drop" />
        </properties>
    </persistence-unit>
</persistence>