连贯性和容器管理的交易

时间:2013-11-20 09:01:52

标签: java jboss transactions ejb oracle-coherence

我正在实现同时写入数据库和Oracle Coherence 3.7.1,并希望使整个操作成为事务性的。

我想对我的方法进行批评。

目前,我已经创建了这样的façade类:

public class Facade {
   @EJB
   private JdbcDao jdbcDao;
   @EJB
   private CoherenceDao coherenceDao;

   @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
   private void updateMethod(List<DomainObject> list) {
      jdbcDao.update(list);
      coherenceDao.update(list);
   }
}

我猜JDBC DAO不需要对事务做任何具体的事情,Hibernate会抛出某种RuntimeException。

public class JdbcDao {
   private void update(List<DomainObject> list) {
       // I presume there is nothing specific I have to do about transactions.
       // if I don't catch any exceptions it would work just fine
   }
}

这是有趣的部分。如何进行Coherence支持交易? 我想我应该在update()方法中打开coherence事务,在其中的任何异常中我应该自己抛出RuntimeException吗?

我目前正在考虑这样的事情:

public class CoherenceDao {
   private void update(List<DomainObject> list) {
      // how should I make it transactional?
      // I guess it should somehow throw RuntimeException?

      TransactionMap mapTx = CacheFactory.getLocalTransaction(cache);
      mapTx.setTransactionIsolation(TransactionMap.TRANSACTION_REPEATABLE_GET);
      mapTx.setConcurrency(TransactionMap.CONCUR_PESSIMISTIC);

      // gather the cache(s) into a Collection
      Collection txnCollection = Collections.singleton(mapTx);

      try {
         mapTx.begin();

         // put into mapTx here

         CacheFactory.commitTransactionCollection(txnCollection, 1);
      } catch (Throwable t) {
         CacheFactory.rollbackTransactionCollection(txnCollection);
         throw new RuntimeException();
      }

   }
}

这种方法会按预期工作吗?

1 个答案:

答案 0 :(得分:0)

我知道你一年前问了这个问题,现在我的答案可能不会像你一年后的价值那么多,但我还是试一试。

只要在coherenceDao.update(list);的方法调用之后没有RuneTimeException,您尝试执行的操作可能会假设您在该行之后没有任何代码行但是&#39 ;不是整个故事。

作为示例:您的数据库中可能有一些可延迟的约束。当容器尝试提交updateMethod(List<DomainObject> list)的方法退出时以及方法调用coherenceDao.update(list)之后的事务时,将应用这些约束。另一种情况就像执行coherenceDao.update(list)之后但仍在事务提交之前的数据库连接超时。 在这两种情况下,CoherenceDAO类的更新方法都是安全可靠的,并且您的一致性事务不再回滚,这将使您的缓存处于不一致状态,因为您将获得RuneTimeException,因为那些DB或Hibernate Exceptions会导致您的容器托管交易要回滚!

相关问题