2017-09-12 6 views
0

L'extrait suivant fonctionne en jeu pour Scala:Déclarant connexion JNDI non par défaut pour l'accès JPA en jeu pour Scala

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

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

Dans application.conf I défini db.default.jndiName=DefaultDS et jpa.default=defaultPersistenceUnit.

Maintenant, j'ai aussi besoin de définir une autre connexion JNDI db.another.jndiName=AnotherDS avec jpa.another=anotherPersistenceUnit.

Lorsque le persistence.xml est:

<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> 

Comment injecter AnotherDS dans l'application de sorte qu'il peut être utilisé avec JPAApi?

Répondre

1

Vous pouvez spécifier plusieurs configurations JPA dans 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 

Dans votre DAO, injecter JPAApi que vous faites actuellement. Utilisez JPAApi#em(String) pour obtenir le EntityManager pour un nom de l'unité de persistance spécifique:

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 { 
     ... 
    } 
    } 

En outre, l'annotation @Transactional est inutile si vous utilisez JPAApi#withTransaction.