且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

不能在persistence.xml中读取环境变量

更新时间:2022-10-31 09:19:34

使用$数据库URL中的{myDataDir}无效,除非您的数据库支持,或者除非您在自己的构建脚本中翻译变量。



您可以做的是将属性映射传递给具有所需URL的Persistence.createEntityManagerFactory(),您必须在运行时在代码中构建。


I have a Maven3 project where I'm using the tomcat7-maven-plugin. I would like to set the path for the embedded database via an environment variable argument to the jvm.

Reading the variable with System.getenv("myDataDir") within a Java-Method returns the correct path. But when I try to set the variable ${myDataDir} in my persistence.xml and then I start tomcat with "mvn tomcat:run" I get FileNotFoundExceptions because the variable is not replaced with the actual value (it says e.g. Cannot find path for ${myDataDir}\derby.log)

I don't know what's causing this - if it's the persistence provider (EclipseLink) that doesn't support this or if it's something else.

My persistence.xml looks like this:

<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" version="2.0" xmlns="http://java.sun.com/xml/ns/persistence">
  <persistence-unit name="myPersistence" transaction-type="RESOURCE_LOCAL">
    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
    <properties>
      <property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.EmbeddedDriver" />
      <property name="javax.persistence.jdbc.url" value="jdbc:derby:${myDataDir}/DB;create=true;upgrade=true" />
      <property name="javax.persistence.jdbc.user" value="admin" />
      <property name="javax.persistence.jdbc.password" value="password" />
      <property name="eclipselink.ddl-generation" value="create-tables" />
      <property name="eclipselink.ddl-generation.output-mode" value="both" />
      <property name="eclipselink.logging.level" value="SEVERE" />
      <property name="eclipselink.logging.file" value="${myDataDir}/derby.log" />
      <property name="eclipselink.application-location" value="${myDataDir}/dbScripts" />
    </properties>
  </persistence-unit>
</persistence>

EDIT:

I forgot to mention, that I'm in a Spring 3 Framework environment. According to the examples on the web, this should be capable of using environment variables in persistence.xml...

Using ${myDataDir} in a database URL is not valid, unless supported by your database, or unless you are translating the variable during your own build scripts.

What you can do is pass a properties map to Persistence.createEntityManagerFactory() that has the URL you want, that you must build at runtime in code.