我正在实现同时写入数据库和 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();
}
}
}
这种方法会按预期工作吗?