我希望我的应用程序 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_1_0.xsd"
version="1.0">
<persistence-unit name="appName" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.dialect" value="${db.dialect'}"/>
<property name="javax.persistence.jdbc.driver" value="${db.driver}"/>
<property name="javax.persistence.jdbc.user" value="${db.user}"/>
<property name="javax.persistence.jdbc.password" value="${db.password}"/>
<property name="javax.persistence.jdbc.url" value="${db.url}"/>
</properties>
</persistence-unit>
</persistence>
从我的源文件夹中某处的简单文本文件中获取这些占位符值。
我读到过使用 Spring 做这样的事情是可能的
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<value>classpath:com/foo/jdbc.properties</value>
</property>
</bean>
但是这里我们没有使用 Spring,只有 Hibernate 和一些 Primefaces。
这可能吗?
谢谢!
编辑:我没有提到一些事情,但作为引用,我也使用 Shiro Security 和 Ant 来做一些事情。我将发布解决方案作为答案。这使我的项目有 3 个带有数据库参数的不同文件:
- persistence.xml( hibernate )
- context.xml(四郎)
- database.properties(用于 Ant 中的 Flyway 任务)
最佳答案
除了在 persistence.xml
中定义属性外,您还可以在标准属性文件 (key=value) 中定义它们,并将 Properties
对象传递给 createEntityManagerFactory()
方法,例如:
Properties props = new Properties();
props.load(new FileInputStream("/some/path/persistence.properties"));
EntityManagerFactory factory = Persistence.createEntityManagerFactory("appName", props);
关于java - persistence.xml 从 .properties 文件导入数据库参数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19170876/