代码之家  ›  专栏  ›  技术社区  ›  ps0604

为Scala中的JPA访问声明非默认JNDI连接

  •  0
  • ps0604  · 技术社区  · 7 年前

    class MyDAO @Inject() (jpaApi: JPAApi) {      
    
      @Transactional
      def someMethod = {
        jpaApi.withTransaction {   // ....
    

    application.conf 我定义了 db.default.jndiName=DefaultDS jpa.default=defaultPersistenceUnit

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

    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

    1 回复  |  直到 7 年前
        1
  •  1
  •   Jeffrey Chung    7 年前

    您可以在中指定多个JPA配置 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
    

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

    @Transactional 如果您正在使用 JPAApi#withTransaction