无法注入persistence.xml中声明的EntityManager

时间:2014-06-03 09:01:14

标签: java jpa persistence.xml cdi-unit

我正在尝试开发一个(基于Maven的)jar库,它可以充当我的Java应用程序的DAL。

这是我的persistence.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<persistence 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"
             version="2.0">

   <persistence-unit name="DALPersistenceUnit" transaction-type="JTA">
      <provider>org.hibernate.ejb.HibernatePersistence</provider>
      <jta-data-source>java:app/env/MyDataSource</jta-data-source>          
      <shared-cache-mode>NONE</shared-cache-mode>
      <properties>
         <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect"/>
      </properties>
   </persistence-unit>
</persistence>

这是DataSource定义,使用@DataSourceDefinition注释

完成
import javax.annotation.sql.DataSourceDefinition;
import javax.ejb.Startup;


@DataSourceDefinition(name = "java:app/env/MyDataSource",
                      className = "com.mysql.jdbc.Driver",
                      serverName="<serverIP>",
                      portNumber=3306,
                      user = "<username>",
                      password = "<pwd>",
                      databaseName = "<dbname>",
                      minPoolSize = 0,
                      initialPoolSize = 0
                      )
@Startup
public class MyDataSource {

}

这是从EntityManager定义中检索persistence.xml的DAO(我使用QueryDSL来简化查询定义)

package my.dal.dao;
import my.domain.dal.QUser;
import my.domain.dal.User;

import javax.enterprise.inject.Default;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceContextType;

import com.mysema.query.jpa.JPQLQuery;
import com.mysema.query.jpa.impl.JPAQuery;

@Default
public class UserDAO {

    @PersistenceContext(unitName = "DALPersistenceUnit", type = PersistenceContextType.EXTENDED)
    private EntityManager entityManager;

    public User getMark()
    {
        QUser qUser = QUser.user;
        JPQLQuery query = new JPAQuery(entityManager);          
        User mark = query.from(qUser).where(qUser.username.eq("mark")).uniqueResult(qUser);
        return mark;
    }       
}

另外,我在beans.xml文件夹

中添加了META-INF文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://java.sun.com/xml/ns/javaee"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
   http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">

</beans>

这是测试类(我使用CDI-Unit进行CDI测试)

import my.dal.dao.UserDAO;
import my.domain.dal.User;
import static org.junit.Assert.assertTrue;
import javax.inject.Inject;
import org.jglue.cdiunit.CdiRunner;
import org.junit.Test;
import org.junit.runner.RunWith;

@RunWith(CdiRunner.class)
public class DALUserTest {

    @Inject UserDAO userDAO;

    @Test
    public void testGetMark()
    {
        User user = userDAO.getMark(); // Here I get a NullPointerException
        assertTrue(user.getUsername()=="mark");
    }
}

当我运行测试时,我在测试类的标记行上得到NullPointerException。此外,如果我调试测试,我可以看到EntityManager entityManager类的UserDAO字段为null,因此不会从persistence.xml文件中注入。

我是否遗漏了Java持久性/ CDI机制中的内容?

谢谢

编辑1:我已将Maven依赖项添加到

querydsl-core:3.3.2
querydsl-apt:3.3.2
querydsl-jpa:3.3.2
log4j:1.2.16
mysql-connector-java:5.1.29
hibernate-entitymanager:4.3.1.Final
hibernate-validator:5.0.3.Final
cdi-unit:3.0.1
junit:4.11
javaee-api:7.0
hibernate-jpa-2.0-api:1.0.1.Final
hibernate-core:4.3.1.Final
hibernate-commons-annotations:4.0.4.Final

编辑2:关注@earthling建议,我在beans.xm l文件中添加了以下bean定义

<bean id="entityManagerFactory" class="org.hibernate.jpa.internal.EntityManagerFactoryImpl">
    <property name="persistenceUnitName" value="DALPersistenceUnit" />
    <property name="persistenceXmlLocation" value="classpath*:/src/main/resources/META-INF/persistence.xml" />
</bean> 

但是我在beans.xml文件

中收到以下错误
  

cvc-complex-type.2.4.a:找到无效的内容   元素&#39; bean&#39;。之一   &#39; {&#34; http://java.sun.com/xml/ns/javaee&#34;:拦截器,&#34; http://   java.sun.com/xml/ns/javaee":decorators,   &#34; http://java.sun.com/xml/ns/javaee&#34;:替代}&#39;是预期的。

2 个答案:

答案 0 :(得分:1)

您正在配置数据源两次。在persistence.xml中并通过@DataSourceDefinition

由于您未在应用程序服务器中运行测试,因此需要produce an EntityManager yourself。一个好主意是使用一个EntityManagerProducer,它可以替换为运行测试。

@RequestScoped
public class EntityManagerProvider {

    @PersistenceContext
    private EntityManager entityManager;

    @Produces
    public EntityManager getEntityManager() {
        return entityManager;
    }

}

然后你需要一个Test-EntityManager Producer

@Alternative
@RequestScoped
public class EntityManagerProvider {


    private EntityManager entityManager;

    @Produces
    public EntityManager getEntityManager() {
        if(entityManager == null) {
            EntityManagerFactory emf = Persistence.createEntityManagerFactory("...");
            entityManager = emf.createEntityManager();
        }
        return entityManager;
    }

}

您可以通过这种方式访问​​EntityManager @Inject private EntityManager em

答案 1 :(得分:-1)

尝试在bean xml中创建entityManagerFactory并通过构造函数注入注入到DAO类

<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
         <property name="persistenceUnitName" value="DALPersistenceUnit" />
        <property name="persistenceXmlLocation" value="classpath*:/<path-to>/persistence.xml" />
</bean>