【问题标题】:Declaring non-default JNDI connection for JPA access in Play for Scala在 Play for Scala 中为 JPA 访问声明非默认 JNDI 连接
【发布时间】:2017-09-12 01:14:17
【问题描述】:

以下 sn-p 适用于 Play for Scala:

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

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

application.conf 中我定义了db.default.jndiName=DefaultDSjpa.default=defaultPersistenceUnit

现在,我还需要用jpa.another=anotherPersistenceUnit 定义另一个JNDI 连接db.another.jndiName=AnotherDS

persistence.xml 在哪里:

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

如何在应用程序中注入AnotherDS以便与JPAApi一起使用?

【问题讨论】:

    标签: scala playframework playframework-2.5


    【解决方案1】:

    您可以在application.conf中指定多个JPA配置:

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

    在您的 DAO 中,像您当前所做的那样注入 JPAApi。使用 JPAApi#em(String) 获取特定持久性单元名称的 EntityManager

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

    此外,如果您使用的是JPAApi#withTransaction,则不需要@Transactional 注释。

    【讨论】:

      猜你喜欢
      • 2018-05-12
      • 1970-01-01
      • 1970-01-01
      • 2023-03-14
      • 2018-08-03
      • 2014-10-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-27
      相关资源
      最近更新 更多