1

我有一个使用 tomcat7-maven-plugin 的 Maven3 项目。我想通过 jvm 的环境变量参数设置嵌入式数据库的路径。

在 Java 方法中使用 System.getenv("myDataDir") 读取变量会返回正确的路径。但是,当我尝试在我的 persistence.xml 中设置变量 ${myDataDir} 然后我使用“mvn tomcat:run”启动 tomcat 时,我得到 FileNotFoundExceptions,因为该变量没有被实际值替换(它说例如找不到路径${myDataDir}\derby.log)

我不知道是什么原因造成的——如果是持久性提供程序 (EclipseLink) 不支持这个,或者是其他原因。

我的 persistence.xml 看起来像这样:

<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>

编辑:

我忘了提,我在 Spring 3 Framework 环境中。根据网上的例子,这应该可以在persistence.xml中使用环境变量...

4

1 回答 1

1

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

你可以做的是将一个属性映射传递给 Persistence.createEntityManagerFactory() ,它具有你想要的 URL,你必须在运行时在代码中构建它。

于 2013-06-18T13:39:16.827 回答