【问题标题】:dynamic "jta-data-source" prop in persistence.xmlpersistence.xml 中的动态“jta-data-source”道具
【发布时间】:2014-09-29 08:03:40
【问题描述】:

我有一个应用程序安装在不同的服务器上 每个服务器都有不同的 jdbc 名称 jdbc 名称也在所有服务器中的 (java) system-prop "jdbc_name" 下定义

我尝试动态更改“jta-data-source”以使用来自 system-prop("jdbc_name") 的值

现在 就我而言,我使用

@PersistenceContext(unitName="MyUnit")
private EntityManager em;

persistence.xml:

 <persistence-unit name="MyUnit" transaction-type="JTA">
    <provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider>
    <jta-data-source>jdbc/myJdbcName</jta-data-source>
    <class>com.myCom.myClass</class>
    <properties>
       <property name="openjpa.TransactionMode" value="managed"/>
    </properties>
</persistence-unit>

我正在使用: 网络球 ejb3 openjpa

【问题讨论】:

    标签: jdbc ejb-3.0 openjpa


    【解决方案1】:

    据我所知,如果您使用容器管理的实体管理器,现在有办法做到这一点。

    您将不得不求助于应用程序管理的实体管理器,并且为了不进行手动工作,您可以将其与 CDI 集成。 这将涉及手动管理事务边界。为了避免这种手动的事务边界管理,可以使用拦截器:

    @ApplicationEntityManagerInterceptorBinding
    @Interceptor
    public class ApplicationEntityManagerInterceptor {
    
      @Inject
      @ApplicationEntityManager
      private EntityManager em;
    
      @AroundInvoke
      public Object intercept(final InvocationContext ic) {
       //check if transaction is active, otherwise create a new one
       em.createTransaction....
       try {
        return ic.proceed();
       } catch (Exception ex) {
         //does the exception require rollback? rollback the transaction here
       } finally {
         //commit the transaction if necessary.
       }
      }
    }
    
    @Stateless
    public class EntityManagerFactoryProducer {
    
      @Produces
      @ApplicationEntityManager
      public EntityManager entityManager() {
        final EntityManagerFactory emf = Persistence.createEntityManager("persistence_name");
        return emf.createEntityManager();
      }
    
      //you will have to manage this yourself
      public void dispose(@Dispose final EntityManager em) {
        em.close();
      }
    }
    

    然后在任何你需要的地方!

    @Stateless
    @ApplicationEntityManagerInterceptorBinding
    public class MyDAO {
      @Inject
      @ApplicationEntityManager
      private EntityManager em;
    }
    

    【讨论】:

    • 我知道有一段时间了,但我看不出这种组合如何帮助动态改变“jta-data-source”.. 还有其他选择吗?
    猜你喜欢
    • 2011-05-02
    • 2015-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-16
    • 2019-01-02
    • 2013-09-20
    • 1970-01-01
    相关资源
    最近更新 更多