【问题标题】:Hibernate fails on sessionFactory.getCurrentSession()休眠在 sessionFactory.getCurrentSession() 上失败
【发布时间】:2026-02-10 07:20:05
【问题描述】:

我想保存具有唯一字段的实体。我不想检查约束是否被违反,我只想以某种方式跳过DataIntegrityViolationException

我发现我可以通过以下方式做到这一点:

@Transactional
wrapperMethod() {
    methodWhenInsertIsDone();
}

@Transactional(propagation = Propagation.REQUIRES_NEW)
methodWhenInsertIsDone() {
    failingMethod();
}

failingMethod(){
    sessionFactory.getCurrentSession().blablabla()
}

当我运行它时,我得到以下异常:

HibernateException: Could not obtain transaction-synchronized Session

所有这些方法都在服务层类中。 @EnableTransactionManagement 存在,HibernateTransactionManager 已定义。没有@Transactional,一切正常。

能否请您告诉我这里出了什么问题或/或者建议另一种方法来吞下DataIntegrityViolationException 异常而无需 try/catch 块。

提前感谢您的每一个想法!

更新:我将methodWhenInsertIsDone 移动到另一个类中,因为现在它不是从代理对象调用的。

更新:异常消失但Propagation.REQUIRES_NEW 无济于事。所以现在我需要寻找其他解决方案燕子DataIntegrityViolationException。如果你有任何请告诉我。我可以为它创建一个新问题。

【问题讨论】:

  • 包括您的配置。此外,如果所有这些类都在一个类中,您对 methodWhenInsertIsDone 的调用将不会导致新事务。
  • @M. Deinum 谢谢,我也找到了。我会更新这个问题。我想我将不得不将methodWhenInsertIsDone 方法移动到另一个类。

标签: java spring hibernate exception-handling spring-transactions


【解决方案1】:

我已将 methodWhenInsertIsDone 移到另一个类中,因为它不是从代理对象调用的。异常消失了。

但是Propagation.REQUIRES_NEW 没有帮助。所以现在我需要寻找其他解决方案来吞下DataIntegrityViolationException。如果你有任何请告诉我。我可以为它创建一个新问题。

【讨论】: