如何外化JPAs persistence.xml中的属性?

sta*_*ker 22 java hibernate seam jpa java-ee

我想将一些hibernate配置放在属性文件中,以使其在没有构建和部署的情况下可编辑.

我尝试通过遵循Create JPA EntityManager中没有persistence.xml配置文件的指示来解决我的问题

app.properties:

hibernate.show_sql=true 
hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.hbm2ddl.auto=validate 
hibernate.show_sql=true
hibernate.format_sql=true
hibernate.default_schema=myschema
Run Code Online (Sandbox Code Playgroud)

persistence.xml中

<?xml version="1.0" encoding="UTF-8"?>
<!-- Persistence deployment descriptor for dev profile -->
<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_1_0.xsd" 
             version="1.0">

   <persistence-unit name="pu">
      <provider>org.hibernate.ejb.HibernatePersistence</provider>
      <jta-data-source>jdbc/appDatasource</jta-data-source>
      <properties>
         <property name="jboss.entity.manager.factory.jndi.name" value="java:/appEntityManagerFactory"/>
      </properties>
   </persistence-unit>

</persistence>
Run Code Online (Sandbox Code Playgroud)

在初始化代码中,应用程序执行以下序列(找到属性),

Properties props = new Properties();
InputStream is = ClassLoader.getSystemResourceAsStream( "app.properties" );
props.load( is );
Persistence.createEntityManagerFactory( "pu", props );
Run Code Online (Sandbox Code Playgroud)

但失败并显示错误消息:

 INFO  [SessionFactoryImpl] building session factory
 INFO  [SessionFactoryObjectFactory] Not binding factory to JNDI, no JNDI name configured
ERROR [STDERR] javax.persistence.PersistenceException: [PersistenceUnit: pu] Unable to build EntityManagerFactory
Run Code Online (Sandbox Code Playgroud)

有谁知道我的配置有什么问题?

版本:JBoss 4.3 Seam:2.1.2

编辑:

JBoss JNDI将"pu"作为持久性单元:

persistence.units:ear=app.ear,jar=app.jar,unitName=pu (class: org.hibernate.impl.SessionFactoryImpl)
Run Code Online (Sandbox Code Playgroud)

Pas*_*ent 9

作为当前方法的替代方案,并且由于您正在使用Hibernate,您可以使用Hibernate通过hibernate.cfg.xml使用hibernate.ejb.cfgfile属性声明文件来配置JPA ,如下所示:

<persistence>
 <persistence-unit name="manager1" transaction-type="JTA">
    <jta-data-source>java:/DefaultDS</jta-data-source>
    <properties>
       <property name="hibernate.ejb.cfgfile" value="/hibernate.cfg.xml"/>
    </properties>
 </persistence-unit>
</persistence>
Run Code Online (Sandbox Code Playgroud)

我的理解是,hibernate.cfg.xml它应该位于类路径上(因此它可能位于打包存档之外).

参考

  • 什么是javax.persistence/EclipseLink的解决方案? (2认同)