【问题标题】:What is the impact of explicitly start and commit a transaction while transaction-type is JTA?当事务类型为 JTA 时,显式启动和提交事务有什么影响?
【发布时间】:2019-04-08 07:37:00
【问题描述】:

我正在开发一个将部署在Weblogic 上的J2EE 应用程序,它包含两层:

  1. 业务:DAO 和逻辑方法
  2. EJB:将使用业务层

我将两层分开,以便能够在 Java SE 项目中重用业务层(作为 jar 库)。

我使用transaction-type = JTA 让服务器管理事务,但在SE 项目中我使用transaction-type = RESOURCE_LOCAL,所以我需要明确开始并提交事务。

所以问题是:如果我在使用JTA 时显式启动并提交事务有什么问题吗?

换句话说,以下两个代码之间是否存在巨大差异:

public void create(T entity) {

    entityManager.persist(entity);

}

public void create(T entity) {

    entityManager.getTransaction().begin(); 
    entityManager.persist(entity);
    entityManager.getTransaction().commit();

}

【问题讨论】:

    标签: java jpa transactions jta


    【解决方案1】:

    您在手动处理交易时应该更加谨慎。始终有一个安全网以防发生异常以回滚您的操作:

          try {
            EntityTransaction transaction = entityManager.getTransaction();
            transaction.begin();
            try {
                entityManager.persist(entity);
                transaction.commit();
            } catch (Exception e) {                
                transaction.rollback(); 
                throw e; // optional if you want to manage the exception higher up                         
            } finally {
              entityManager.close(); // optional if you also manage you EM creation manually.
             } 
    

    【讨论】:

    • 感谢您的回答,所以这不会造成使用transaction-type = JTA 时失去一些好处的负面影响
    • 您的交易将具有与 CMT 相同的配置道具。您只需要管理开始/结束/处理异常。
    猜你喜欢
    • 2013-06-21
    • 2013-09-20
    • 1970-01-01
    • 1970-01-01
    • 2015-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多