Spring:在提交时捕获 ConstraintViolationException
我正在使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可能正在使用
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 callSession.flush()
inside of theobjectClassDAO.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 beforeobjectClassDAO.delete
returns. This may be a last resort though.