我有两种方法:
public void removeObject(CustomObject o){
Transaction tx = null;
try (Session session = HibernateUtil.getSessionFactory().openSession()) {
tx = session.beginTransaction();
session.delete(o);
tx.commit();
} catch (HibernateException e) {
if (tx != null) tx.rollback();
throw new HibernateException(e.getMessage());
}
}
和
public void createF(F f){
Transaction tx = null;
try (Session session = HibernateUtil.getSessionFactory().openSession()) {
tx = session.beginTransaction();
session.save(f);
tx.commit();
} catch (HibernateException e) {
if (tx != null) tx.rollback();
throw new HibernateException(e.getMessage());
}
}
如果其中任何一个出现问题,它将被回滚。
但是,如果我想要我的业务逻辑怎么办?
我可以做类似的事情:
try{
dbDAO.removeObject(o);
// some logic
dbDAO.createF(f)
}catch(Exception e ) {...}
如果createF()
函数中发生错误,则removeObject()
已在数据库中删除,并且在实现中已提交更改,因此即使createF()
失败并回滚,它也不会回滚从removeObject()
开始更改。
如何处理这种情况?我是否必须创建另一个函数,例如:
public void removeAndCreate(F f,CustomObject o){
Transaction tx = null;
try (Session session = HibernateUtil.getSessionFactory().openSession()) {
tx = session.beginTransaction();
session.delete(o);
// some locis
session.save(f);
tx.commit();
} catch (HibernateException e) {
if (tx != null) tx.rollback();
throw new HibernateException(e.getMessage());
}
}
换句话说,我不能重用这两种方法,或者有什么技术可以让我在这种情况下重用这些方法?
我可以想象很多逻辑需要组合多个DAO方法,因此为N个操作创建另一种组合方法将是很多工作。
感谢您的帮助!我正在使用休眠5和spring