gpt4 book ai didi

java - 用于事务重用的 Hibernate 模式

转载 作者:行者123 更新时间:2023-11-29 06:44:12 25 4
gpt4 key购买 nike

我正在编写一个基本方法,以便不一遍又一遍地重复相同的 hibernate session /事务逻辑。这相当简单,但有一个具体问题我不确定可以用这种方法解决。

假设您有一个用户实体和一个权限实体。如果请求保存用户及其匹配权限,那么我认为在单个事务中执行这两个操作是有意义的,因为只能保存其中一个实体可能被视为数据损坏。例如,未能保存用户权限将导致回滚之前插入的用户数据。

我创建了以下方法以允许在必要时可以与当前事务一起工作的通用 hibernate 操作,尽管我现在认为在其当前形式下它不会工作,因为调用 session.beginTransaction();可能会返回一个新事务,即使之前的事务尚未提交(是这种情况吗?)。假设我更改它以使其返回当前 session 和事务,如果指定对当前事务进行更多操作,您认为这行得通吗?做这样的事情是否可取,或者您会建议改变方法吗?谢谢

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();
}
}
}

最佳答案

“建议”是停止尝试重写已经编写、调试、拖入泥潭、调试更多并部署了数千次的代码。即,您遇到的问题和注意事项之前已经遇到和克服,并且解决方案已被证明。此外,经过广泛使用和改进,与您在自定义解决方案中投入的内容相比,它们使用起来需要的努力要少得多。查看Spring's Hibernate support , 特别是 "Implementing DAOs based on plain Hibernate 3 API"和“Declarative transaction demarcation”。为了进一步阅读,有一个完整的 chapter on transaction management .

我有一个 sample project on github您可以在其中看到一个非常简单的示例,该示例使用 Spring 在 Web 应用程序的上下文中管理 Hibernate session 和事务(使用 Spring MVC)。

更新:对于那些后来出现的人,这样他们就不必深挖评论了:

使用Spring的事务处理一般有3种方式:声明式defining which methods are transactional with XML , 声明性地 annotating methods as @Transactional ,或以编程方式 using TransactionTemplate .

关于java - 用于事务重用的 Hibernate 模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7816025/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com