我有一个由 Spring 框架维护的 EntityManager
对象,我使用像这样的 @PersistenceContext
注释将它注入(inject)到我想要的任何 DAO 类中。
@PersistenceContext(unitName="entityManager")
private EntityManager em;
我使用那些 DAO 类在数据库中保存类似这样的东西..
class MyClass
{
@Resource(name="myDao")
private MyDao dao;
@Resource(name="myAnotherDao")
private MyAnotherDao anotherDao;
public void save(String s1,String s2)
{
try
{
MyEntity m=new MyEntity();
m.setName(s1);
// .. and so on ..
XYZ x=new XYZ();
x.setDEF(s2);
anotherDao.save(x);
m.setXYZ(x);
// .. some other stuff .. //
dao.saveEntity(m);
}
catch(Exception e)
{
// I would like to rollback the transaction
}
}
}
现在,这里的两个 daos 使用相同的 EntityManager
通过 @PersistenceContext(unitName="entityManager")
注入(inject)。现在,如果在 setXYZ()
之后发生异常,那么我什至想回滚已保存的 XYZ
实体。但是,如何从中获取 EntityManager
?
如果所有的 daos 都持有相同的对象,那么我可以只调用 EntityManager
类的 getTransaction().rollback()
方法吗? getTransaction()
是否返回新交易或当前与 EntityManager
关联的任何交易?
最佳答案
如果你使用Spring AOP来管理事务,并且配置和注解使用得当,默认的效果是当运行异常发生时,事务会被回滚。
如果您手动管理事务,您可以像这样回滚事务:
EntityManager em = createEntityManager(); try { em.getTransaction().begin(); // Do something with the EntityManager such as persist(), merge() or remove() em.getTransaction().commit(); } catch(Exception e) { em.getTransaction().rollback(); } em.close();
查看更多信息: http://en.wikibooks.org/wiki/Java_Persistence/Transactions http://www.developerscrappad.com/547/java/java-ee/ejb3-x-jpa-when-to-use-rollback-and-setrollbackonly/#sthash.jx3XlK5m.dpuf
关于java - 如何在 JPA 中回滚事务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26200324/