我有一个由
Spring框架维护的EntityManager对象,我使用@PersistenceContext注释将其注入到我想要的任何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都使用通过@PersistenceContext(unitName =“entityManager”)注入的相同EntityManager.现在,如果在setXYZ()之后发生异常,那么我甚至想要回滚保存的XYZ实体.但是,我如何从中获取EntityManager?
如果所有的daos都拥有相同的对象,那么我可以只调用EntityManager类的getTransaction().rollback()方法吗? getTransaction()是返回新事务还是当前与EntityManager关联的任何事务?
892

被折叠的 条评论
为什么被折叠?



