Sai prateek
Sai prateek

Reputation: 11896

Can we set JTA datasource name in properties file

Can we set the JTA datasource name in properties file , which will be read in persistance.xml of application.

Upvotes: 0

Views: 1233

Answers (2)

kostja
kostja

Reputation: 61538

There is another, simpler possibility to have your datasource name and other application parameters configurable.

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.

EDIT:

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 -Pdatasource,db_test

Upvotes: 1

Glenn Lane
Glenn Lane

Reputation: 4010

You can override values in your persistence.xml file by dynamically generating an EntityManagerFactory using Persistence.createEntityManagerFactory(persistenceUnitName, properties), and using the properties map to specify the datasource name. However, now you can never inject an EntityManager using @PersistenceContext, or inject EntityManagerFactory using @PersistenceUnit anywhere in your application, and you have to manually manage your EntityManager transactions. Don't do it. This is a terrible idea.

Upvotes: 1

Related Questions