How to use environment variables in persistence.xml ?

In this short tutorial we will show how to use variables in your persistence.xml so that you can dynamically specify the data source which is used by our application.

In WildFly the simplest and most elegant way to do that is enabling the property replacement in the ee subsystem, as in the following example:

<subsystem xmlns="urn:jboss:domain:ee:4.0">
      <spec-descriptor-property-replacement>true</spec-descriptor-property-replacement>
      <jboss-descriptor-property-replacement>true</jboss-descriptor-property-replacement> 
. . .
</subsystem>

Now you can use the BeanShell expression with the env prefix to reference environment variables. For example:

<property name="javax.persistence.jdbc.url" value="jdbc:mysql://${env.MYSQL_DB_HOST}:${env.MYSQL_DB_PORT}/mydbname"/> 
<property name="javax.persistence.jdbc.user" value="${env.MYSQL_DB_USERNAME}"/> 
<property name="javax.persistence.jdbc.password" value="${env.MYSQL_DB_PASSWORD}"/>

This strategy is particularly useful in cloud environment such as Openshift, where you can pass environment variables to your Applications, in order to customize them.

Earlier versions of JBoss AS

In earlier versions of JBoss AS (such as JBoss EAP 7) the approach was a bit different: you needed to wrap the dynamic part as variable using the ${variable} syntax. Later on you can specify the value for the variable using the -D option.

Let’s take as sample the persistence.xml which is part of the Kitchensink quickstarts.

Here is it, using the ${myds} variable instead of the “java:jboss/datasources/KitchensinkQuickstartDS”:

<persistence version="2.0"
   xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="
        <a href="http://java.sun.com/xml/ns/persistence">http://java.sun.com/xml/ns/persistence</a>
        <a href="http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd</a>">
   <persistence-unit name="primary">
      <jta-data-source>${myds}</jta-data-source>
      <properties>
         <!-- Properties for Hibernate -->
         <property name="hibernate.hbm2ddl.auto" value="create-drop" />
         <property name="hibernate.show_sql" value="false" />
      </properties>
   </persistence-unit>
</persistence>

That’s all. Now start the application server with:

standalone.bat -Dmyds=java:jboss/datasources/KitchensinkQuickstartDS

Or (if you are using JBoss AS 4-5-6):

run.bat -Dmyds=java:jboss/datasources/KitchensinkQuickstartDS

Found the article helpful? if so please follow us on Socials