我需要使用2个实体管理器来实现2个流程,并且想手动控制第二个实体管理器的事务,因为它可以回滚或基于逻辑提交。
因为它们的过程是交错的,所以我不能将它们的过程移到一种公共方法上并为其使用新的事务。
我打算按照以下方式实施,但不确定是否正确。
我的问题:
我的示例源代码
@Service
@Transactional
class MainService extends BaseServices {
@PersistenceContext
private EntityManager entityManagerFirst;
public void method1(boolean flg) {
try {
method2(); // execute with entityManagerFirst
if (flg) {
EntityManager entityManagerSub = getEntityManagerFactory().createEntityManager();
entityManagerSub.getTransaction().begin();
// process 1
method3(entityManagerSub); // do with entityManagerSecond
// process 2
method4(); // execute with entityManagerFirst
// process 3
boolean result3 = method5(entityManagerSub); // do with entityManagerSecond
if (result3) {
entityManagerSecond.getTransaction().commit();
} else {
entityManagerSecond.getTransaction().rollback();// need rollback transaction at method3 and method 5
}
} else {
// process 4
method6(); // execute with entityManagerFirst
method7(); // execute with entityManagerFirst
}
} catch (Exception e) {
TransactionAspectSupport.currentTransactionStatus()
.setRollbackOnly(); // set rollback for entityManagerFirst
entityManagerSecond.getTransaction().rollback(); // rollback for entityManagerSecond
}
}
private boolean method3(EntityManager entityManagerSub) {
{
// execute logic with entityManagerSub
if (entityManagerSub != null) {
....
// execute update query with entityManagerSub
entityManagerSub.executeUpdate();
}
}