Read Environment Variables in persistence.xml file

Ran picture Ran · Jan 12, 2012 · Viewed 11.5k times · Source

I want to read environment variables inside persistence.xml file.

Idea is that i don't want my database details to be read from properties file as there is a change of getting properties file override.Instead i want to read details from environment variables.

Is there any way to achieve this criteria.

Iam using Spring 3 my standalone application will be deployed in unix machine.

Answer

Zack Macomber picture Zack Macomber · Jan 12, 2012

You can update properties in a persistence unit by supplying a Map (see this).

Conveniently, environment variables can be retrieved as a Map (see this).

Put the two together and you can dynamically update properties in your persistence unit with environment variables.

EDIT: simple example...

persistence.xml...

<persistence-unit name="default" transaction-type="RESOURCE_LOCAL">
    <provider>
        oracle.toplink.essentials.PersistenceProvider
    </provider>
    <exclude-unlisted-classes>false</exclude-unlisted-classes>
    <properties>
        <property name="toplink.logging.level" value="INFO"/>
        <property name="toplink.jdbc.driver" value="oracle.jdbc.OracleDriver"/>
        <property name="toplink.jdbc.url" value="jdbc:oracle:thin:@myhost:l521:MYSID"/>
        <property name="toplink.jdbc.password" value="tiger"/>
        <property name="toplink.jdbc.user" value="scott"/>
    </properties>
</persistence-unit>

code that updates persistence.xml "default" unit with environment variables...

Map<String, String> env = System.getenv();
Map<String, Object> configOverrides = new HashMap<String, Object>();
for (String envName : env.keySet()) {
    if (envName.contains("DB_USER")) {
        configOverrides.put("toplink.jdbc.user", env.get(envName)));    
    }
    // You can put more code in here to populate configOverrides...
}

EntityManagerFactory emf =
    Persistence.createEntityManagerFactory("default", configOverrides);