【发布时间】:2011-10-19 02:48:57
【问题描述】:
我正在编写一个基本方法,以便不一遍又一遍地重复相同的休眠会话/事务逻辑。这相当简单,但有一个特定的问题我不确定是否可以用这种方法解决。
假设您有一个 User 实体和一个 Permission 实体。如果请求保存用户及其匹配的权限,那么我认为在单个事务中执行这两个操作是有意义的,因为只能保存其中一个实体可能被视为数据损坏。例如,未能保存用户的权限将需要回滚之前插入的用户数据。
我创建了以下方法来允许通用休眠操作,如果有必要,可以与当前事务一起工作,尽管我现在认为在当前形式下它不会在调用 session.beginTransaction(); 后工作。即使前一个尚未提交,也可能会返回一个新事务(是这种情况吗?)。假设我更改它是为了让它返回当前会话和事务,如果指定当前事务会有更多操作,你认为它会工作吗?做这样的事情是否可取,或者你会建议改变方法吗?谢谢
protected <T> void baseOperation(Class<T> entityClass, List<T> instances, BaseHibernateDAO.Operations operation, boolean isLastOperation) throws Exception
{
Session session = null;
Transaction transaction = null;
boolean caughtException = false;
//get session from factory
session = HibernateSessionFactory.getSession();
try
{
//get current transaction
transaction = session.beginTransaction();
for (Object instance : instances) //perform operation on all instances
{
log.debug(String.format("Will perform %s operation on %s instance.", operation.name(), entityClass.getName()));
switch (operation) //perform requested operation
{
case SAVE:
session.save(instance);
break;
case UPDATE:
session.update(instance);
break;
case SAVEORUPDATE:
session.saveOrUpdate(instance);
break;
case DELETE:
session.saveOrUpdate(instance);
break;
}
log.debug(String.format("%s operation on %s instance was succesful.", operation.name(), entityClass.getName()));
}
session.flush(); //synchronize
if (isLastOperation) //if this is the last operation of the transaction
{
transaction.commit();
log.debug("Transaction commited succesfully.");
}
}
catch (Exception e) //error occurred
{
caughtException = true;
//roll-back if transaction exists
if (transaction != null)
{
transaction.rollback();
}
//log and re-throw
log.error("An error occurred during transaction operation.", e);
throw e;
}
finally //cleanup tasks
{
if (isLastOperation || caughtException) //close session if there are no more pending operations or if an error occurred
{
HibernateSessionFactory.closeSession();
}
}
}
【问题讨论】:
标签: java hibernate session transactions