gpt4 book ai didi

java - 一致性和容器管理的事务

转载 作者:太空宇宙 更新时间:2023-11-04 15:23:46 26 4
gpt4 key购买 nike

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

我想对我的方法提出批评。

目前,我创建了这样的外观类:

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() 方法中打开一致性事务,并且对于其中的任何异常我应该自己抛出 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();
}

}
}

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

最佳答案

我知道您一年前就问过这个问题,一年后我现在的回答可能对您来说没有多大值(value),但我仍然尝试一下。

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

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

关于java - 一致性和容器管理的事务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20091417/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com