一尘不染

如何从JPA persistence.xml外部化属性?

hibernate

我想将一些hibernate配置放在属性文件中,以使其无需构建和部署就可编辑。

我尝试按照不带persistence.xml配置文件的Create JPAEntityManager中的说明解决问题

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

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>

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

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

但失败并显示错误消息:

 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

有人知道我的配置可能出什么问题吗?

版本:JBoss 4.3接缝:2.1.2

编辑:

JBoss JNDI将“ pu”列为持久性单元:

persistence.units:ear=app.ear,jar=app.jar,unitName=pu (class: org.hibernate.impl.SessionFactoryImpl)

阅读 297

收藏
2020-06-20

共1个答案

一尘不染

作为当前方法的替代方法,并且由于使用的是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>

我的理解是hibernate.cfg.xml只是应该在classpath上(所以它可能在打包的档案之外)。

参考文献

2020-06-20