persistence.xml从.properties文件导入数据库参数值

编辑: 不重复,但差不多

我想让我的应用程序persistence.xml成为类似的东西

   org.hibernate.ejb.HibernatePersistence          

从我的源文件夹中的某个简单文本文件中获取这些占位符值。

我读到了使用Spring做的可能性

   classpath:com/foo/jdbc.properties   

但是在这里我们不使用Spring,只使用Hibernate和一些Primefaces。

可能吗?

谢谢!

编辑:我没有提到一些东西,但作为参考,我也使用Shiro Security和Ant来做一些事情。 我会发布解决方案作为答案。 这使我的项目有3个不同的文件与数据库参数:

  • persistence.xml(Hibernate)
  • context.xml(Shiro)
  • database.properties(用于Ant中的Flyway任务)

您可以在标准属性文件(key = value)中定义它们,而不是在persistence.xml中定义属性,并将Properties对象传递给createEntityManagerFactory()方法,例如:

 Properties props = new Properties(); props.load(new FileInputStream("/some/path/persistence.properties")); EntityManagerFactory factory = Persistence.createEntityManagerFactory("appName", props); 

如果您使用Maven作为构建系统,则可以使用Mavenfilter在构建期间替换值。

或者你可以编写一个简单的属性占位符替换(由spring本身内部使用)

参考: https : //stackoverflow.com/a/14724719/477435

我编辑提到我正在使用Shiro Security,它还需要一些数据库参数。 我让它只需要1个数据库参数位置,这些位置保留在context.xml中并在其他参考中引用它。

1)Ant读取context.xml

Context.xml有

       

在Ant build.xml中使用过

  

然后使用。访问它

       

2)persistence.xml读取context.xml

可以使用此方法使用上下文的数据存储区

 java:/comp/env/jdbc/postgres 

所以,我将3个数据库参数杀死为1。

谢谢您的帮助!