TomEE + OpenJPA - 无法注入EntityManagerFactory PersistenceUnit

时间:2013-02-11 17:50:50

标签: openjpa openejb persistence.xml apache-tomee

我有一个无状态的EJB注入

@PersistenceUnit 
private EntityManagerFactory factory

我的persistence.xml:

<?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="ejbPU-ro" transaction-type="RESOURCE_LOCAL">
        <provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider>
        <non-jta-data-source>mySQLDataSource</non-jta-data-source>
        <exclude-unlisted-classes>false</exclude-unlisted-classes>
        <properties>
            <property name="openjpa.jdbc.DBDictionary" value="mysql"/>
            <property name="openjpa.jdbc.SynchronizeMappings" value="buildSchema(foreignKeys=true"/>
            <property name="openjpa.jdbc.SchemaFactory" value="native(foreignKeys=true)"/>
            <property name="openjpa.Log" value="DefaultLevel=INFO,SQL=INFO"/>
        </properties>
    </persistence-unit>
</persistence>

我正在使用的单元测试:

Properties p = new Properties();
p.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.openejb.core.LocalInitialContextFactory");
p.setProperty(Context.PROVIDER_URL, "http://127.0.0.1:4204/openejb/ejb");
InitialContext initialContext = new InitialContext(p);

同时定义openejb.home VM arg并且单元测试运行完美。

部署到TomEE时,我在my.war/WEB-INF/lib/my.jar/META-INF中有persistence.xml。

conf/tomee.xml我有:

<JndiProvider id="prov" type="javax.naming.InitialContext">
    java.naming.factory.initial = org.apache.openejb.core.LocalInitialContextFactory
    java.naming.provider.url = http://127.0.0.1:4204/openejb/ejb
</JndiProvider>

<Resource id="mySQLDataSource" type="DataSource">
    JdbcDriver          com.mysql.jdbc.Driver
    JdbcUrl             jdbc:mysql://127.0.0.1:3306/mydb
    UserName            root
    Password        
        JtaManaged      false
        DefaultAutoCommit   false
</Resource>

日志看起来很好但是当我运行代码时,注入的工厂为空。

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

几个东西:

1)您的初始背景:

p.setProperty(Context.INITIAL_CONTEXT_FACTORY,"org.apache.openejb.core.LocalInitialContextFactory");
p.setProperty(Context.PROVIDER_URL, "http://127.0.0.1:4204/openejb/ejb"); <- useless since you are in embedded mode

2)你的web.xml有metadata-complete = true所以禁止扫描(删除它)

3)你通常不需要org.apache.cxf.jaxrs.servlet.CXFNonSpringJaxrsServlet(参见http://svn.apache.org/repos/asf/tomee/tomee/trunk/examples/rest-example-with-application/) - 或者使用JAXRS技巧通过web.xml声明它(IIRC javax.ws.rs .Application as init parameter)

4)不确定你的ajax网址是否正确(在tomee @上提供的样本上)

终于得到了一个非空的emf(在trunk上测试,因为它在这里;)