Spring:在提交时捕获 ConstraintViolationException

发布于 2025-01-08 21:22:34 字数 453 浏览 0 评论 0原文

我正在使用 Hibernate 和 Spring,目前我遇到了一些我认为很容易修复的问题。我有一个与此类似的服务方法:

@Transactional
public void deleteObject(ObjectClass object)
{
    this.objectClassDAO.delete(object);
}

当用户尝试删除与另一个实体相关的对象时,我需要显示一条友好的消息。我遇到的问题是,在调用 commit() 之前会抛出 ConstraintViolationException,这在我的服务方法的范围之外运行。有没有办法让 spring 在发生特定异常时调用一些中间代码,以便我可以设置正确的错误消息?

我在谷歌上搜索了一个多小时,但没有成功。我发现看起来至少有轻微相关的方法似乎有点矫枉过正,而且就像它们在应用程序级别运行一样。有没有一种简单的方法可以在方法级别提交后拦截异常?

I'm using Hibernate and Spring and I'm currently stuck with something which I thought would be very simple to fix. I have a service method similar to this:

@Transactional
public void deleteObject(ObjectClass object)
{
    this.objectClassDAO.delete(object);
}

I need to display a friendly message when the user tries to delete an object which is related to another entity. The problem I have is that the ConstraintViolationException is thrown until commit() is called, which runs outside of the scope of my service method. Is there a way to let spring call some intermediate code in the event of a particular exception, so that I can set the proper error message?

I've been searching on google for over an hour with no luck. The approaches I've found that seem at least mildly related seem like overkill and like they run at application level. Is there a simple way to intercept an exception after a commit at method-level?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

心欲静而疯不止 2025-01-15 21:22:34

您可能正在使用FlushMode.AUTO,并且当事务结束时会抛出异常(在 Spring 创建的服务周围的代理中)。您可以在 objectClassDAO.delete() 方法内显式调用 Session.flush() 。您通常不想这样做,但在这种情况下,它将强制与底层持久性进行同步,并且如果存在约束违规,则会在 objectClassDAO.delete 返回之前抛出异常。但这可能是最后的手段。

You're probably using FlushMode.AUTO and the exception is being thrown when the transaction ends (in the proxy around your service created by Spring). You can explicitly call Session.flush() inside of the objectClassDAO.delete() method. You typically don't want to do this, but in this case it will force a synchronization with the underlying persistence and if there is a constraint violation the exception will be thrown before objectClassDAO.delete returns. This may be a last resort though.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文