Lan*_*ali 5 java spring hibernate jpa transactions
我正在使用JPA和Spring.如果我让Spring处理事务,那么假设EntityManager已正确注入DAO,这就是我的服务层的样子:
MyService {
@Transactional
public void myMethod() {
myDaoA.doSomething();
myDaoB.doSomething();
}
}
Run Code Online (Sandbox Code Playgroud)
但是,如果我要手动执行事务,我必须确保将EntityManager的实例传递到事务中的每个DAO中.任何想法如何更好地重构?我很难做新的MyDaoA(em)或将em传递给每个DAO方法,如doSomething(em).
MyService {
private EntityManagerFactory emf;
public void myMethod() {
EntityManager em = emf.createEntityManager();
EntityTransaction tx = em.getTransaction();
MyDaoA myDaoA = new MyDaoA(em);
MyDaoB myDaoB = new MyDaoB(em);
try {
tx.begin();
myDaoA.doSomething();
myDaoB.doSomething();
tx.commit();
} catch(Exception e) {
tx.rollback();
}
}
}
Run Code Online (Sandbox Code Playgroud)
我猜有点在黑暗中拍摄,但你知道你可以这样做吗:
TransactionInterceptor.currentTransactionStatus().setRollbackOnly();
这通常会消除您希望/需要在具有声明式事务的系统中使用编程式事务的大多数情况。
归档时间: |
|
查看次数: |
6805 次 |
最近记录: |