Declaring non-default JNDI connection for JPA access in Play for Scala

202 Views Asked by At

The following snippet works in Play for Scala:

class MyDAO @Inject() (jpaApi: JPAApi) {      

  @Transactional
  def someMethod = {
    jpaApi.withTransaction {   // ....

In application.conf I defined db.default.jndiName=DefaultDS and jpa.default=defaultPersistenceUnit.

Now, I also need to define another JNDI connection db.another.jndiName=AnotherDS with jpa.another=anotherPersistenceUnit.

Where the persistence.xml is:

<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
             version="2.1">

    <persistence-unit name="defaultPersistenceUnit" transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
        <non-jta-data-source>DefaultDS</non-jta-data-source>
        <properties>
            <property name="hibernate.dialect" value="org.hibernate.dialect.HANAColumnStoreDialect"/>
        </properties>
    </persistence-unit>

    <persistence-unit name="anotherPersistenceUnit" transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
        <non-jta-data-source>AnotherDS</non-jta-data-source>
        <properties>
            <property name="hibernate.dialect" value="org.hibernate.dialect.HANAColumnStoreDialect"/>
        </properties>
    </persistence-unit>

</persistence>

How to inject AnotherDS in the application so it can be used with JPAApi?

1

There are 1 best solutions below

0
Jeffrey Chung On BEST ANSWER

You can specify multiple JPA configurations in application.conf:

db.default.jndiName=DefaultDS
... // other configuration for db.default
jpa.default=defaultPersistenceUnit

db.another.jndiName=AnotherDS
... // other configuration for db.another
jpa.another=anotherPersistenceUnit

In your DAO, inject JPAApi as you're currently doing. Use JPAApi#em(String) to get the EntityManager for a specific persistence unit name:

class MyDAO @Inject() (jpaApi: JPAApi) {

  def someMethodWithDefault = {
    val em = jpaApi.em("default") // em is an EntityManager
    jpaApi.withTransaction {
      ...
    }
  }

  def someMethodWithAnother = {
    val em = jpaApi.em("another") // em is an EntityManager
    jpaApi.withTransaction {
      ...
    }
  }

Also, the @Transactional annotation is unnecessary if you're using JPAApi#withTransaction.