问题
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...
回答1:
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.
来源:https://stackoverflow.com/questions/17044604/not-able-to-read-environment-variable-in-persistence-xml