MetaColon
MetaColon

Reputation: 2871

Use maven properties in persistence.xml

I want to use properties defined in my pom.xml (with different values for different profiles) in my persistence.xml.

More precisely, I'd like the SQL dialect used in the persistence to adjust according to the profile I built my application with. So I'd have to inject a value stored in the profile like that:

<profile>
  <id>profileName</id>
  <properties>
    <SqlDialect>Oracle</SqlDialect>
  </properties>
</profile>

into the persistence.xml:

<property name="hibernate.dialect" value="{maven property goes here}" />

Is this possible? And if not, is there another elegant solution (i.e. another solution than using multiple persistence files for the different dialects)?

Upvotes: 1

Views: 1349

Answers (2)

Jens
Jens

Reputation: 69460

Add the following lines to your pom, so maven knows where the repalce ment should be done:

<build>
    <resources>
        <resource>
            <directory>path to your persistence.xml</directory>
            <filtering>true</filtering>
        </resource>
    </resources>
 ...
</build>

Define a variable in your pom for the property:

<properties>
    <hibernate.dialect>the dialect you want to use</hibernate.dialect>
</properties>

add the variable at a value:

<property name="hibernate.dialect" value="${hibernate.dialect}" />

But pay ATTENTION: all files in the "path to your persistence.xml" will be analyzed. So binary files can be damaged.

So if you have binaray files in the directury you must work with excludes and includes:

<build>
    <resources>
        <resource>
            <directory>path to your persistence.xml</directory>
            <excludes>
                <exclude>define the binary files</exclude>
            </excludes>
            <filtering>true</filtering>
        </resource>
        <resource>
            <directory>path to your persistence.xml</directory>
            <includes>
                <includes>define the binary files</includes>
            </includes>
        </resource>

    </resources>
 ...
</build>

Upvotes: 2

J Fabian Meier
J Fabian Meier

Reputation: 35843

Your persistence.xml is a resource, right?

Then you can configure it as filtered resource in the POM and use ${some-property} to reference the property from the POM.

https://maven.apache.org/plugins/maven-resources-plugin/examples/filter.html

Upvotes: 4

Related Questions