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 simples 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">
. . .

 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 version of JBoss AS

In earlier version 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="" xmlns:xsi=""
   <persistence-unit name="primary">
         <!-- Properties for Hibernate -->
         <property name="" value="create-drop" />
         <property name="hibernate.show_sql" value="false" />

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