-->

Different persistence units for different Maven pr

2019-08-03 05:45发布

问题:

I want to use two different databases depending on the selected Maven profile. For the profile "production" I want to use a MySQL database and for the "development" profile I want to use an in-memory HSQLDB.

I found out that it is possible to have two persistence.xml files. One in "src/main/resources/META-INF" and the other one stored in "src/test/resources/META-INF". This gives the possibility to choose a different database for testing.

But is it also possible to do the database selection depending on the selected Maven profile?

回答1:

This is possible, though without changing the persistence.xml:

We use maven profiles and resource filtering for that. You will need to define placeholders in your persistence.xml that match the property names in your .properties file or in your .pom.

During the build, you specify the profile and maven will replace the placeholders with your properties.

We have used this technique for switching the datasource between different deployment environments. You can also use it for switching PUs or other properties.

First, define a profile for resource filtering:

<profiles>
  <profile>
   <id>set_datasource</id>
     <build>
       <!-- enable resource filter to set the datasource name -->
       <resources>
          <resource>
            <directory>src/main/resources</directory>
            <filtering>true</filtering>
      ...

Create a profile for each datasource:

<profile>
      <id>db_test</id>
    <properties>
      <database.name>test_ds</database.name>
    </properties>
</profile>

In your persistence unit, prepare the placeholder

  <persistence-unit name="my_db">
    <jta-data-source>java:jboss/datasources/${datasource.name}</jta-data-source>
  </persistence-unit>

Call maven with the two profiles:

mvn test -Pset_datasource,db_test

Please note, we use this mainly for UI- and user-tests. For integration/feature tests we use Arquillian. For Arquillian, you can define a separate persistence.xml file, or even create one on-the-fly.