Configurable data-source references in persistence.xml with JBoss properties

This tutorial shows you how to make the data-source references in your persistence.xml configurable.

Why should I do this?

Hard-coding your data-sources in your persistence.xml is not always the best option. You may need to deploy your application on a server which has a data-source with the specific name configured to a different database.
Or you might want to deploy several instances of the same application on the same server.

That is why it can be useful to make your data-source references configurable.

1. Edit your persistence.xml
Initially your persistence.xml may look like this

Where jdbc/MyDataSource maps to a configured data-source on the JBoss Application server.

Now change this jdbc/MyDataSource in java:comp/env/jdbc/MyDataSource.

2. Add resource references to your web.xml
The WEB-INF/web.xml file becomes the link between the reference in the persistence.xml and the property which will be defined in the file

3. Add and configure a file
Create a file in the META-INF folder of your EAR or WAR project.
In this file you specify the value for the MyDataSource variable.

Alternatively you can

  • start your application server with a value for the variable
  • define a value for the variable in the standalone.xml or domain.xml of your JBoss Application server