【发布时间】:2015-07-13 08:05:16
【问题描述】:
我有一个从sessionFactory.openSession() 检索的休眠会话,以及一些对Entities 的复杂计算,并且我想在计算期间持久化(UPDATE, INSERT, DELETE)一些Entities。
这是一个案例:
假设我有一个代表产品的ProductEntity,代表产品订单记录的OrderEntity,以及代表预订产品订单的用户的UserEntity。
我知道我可以通过这种方式处理预订操作:
public void addOrder(UserEntity userEntity, ProductEntity productEntity, int quantity){
session = sf.openSession();
Transaction tx = session.beginTransaction();
//do some compution and generate the orderEntity and persistent it to the db.
try{
tx.commit();
}catch(Exception e){
tx.rollback();
}finnaly{
session.close();
}
}
现在我必须向该过程添加更多操作,例如 (Maybe) 创建一个 NotifyEntity 并存储在 db 中,它代表拥有该产品的商家的通知记录。这个notify 记录可以由orderEntity 生成,与productEntity 或UserEntity 无关,实际上,我希望这个notifyMerchantByOrderEntity 方法从addOrder 过程中分离出来,以便我可以复用这个方法,把代码搞清楚(我真的不想在同一个方法里搞一大堆代码,其实如果校验逻辑够复杂的话,addOrder方法的代码可以很- 很长)。
无论如何,我想:
- 将一个很长的事务分成几个方法
- 但是这些方法应该作为一个整体的事务一起考虑(即当异常发生时它们应该一起回滚)
类似这样的:
public void addOrder(UserEntity userEntity, ProductEntity productEntity, int quantity){
Session session = sf.openSession();
session.beginTransaction();
invokeOtherMethod(); //invoking other method which also contains some db operation.
try{
tx.commit()
}catch(Exception e){
tx.rollback(); //this should rollback the operation in invokeOtherMethod() too.
}finally{
session.close();
}
}
【问题讨论】:
标签: java hibernate session orm transactions