本文介绍了如何在 Spring 中处理 DataIntegrityViolationException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在 Spring 3.0 应用程序中显示自定义消息.我有一个带有 Hibernate 的数据库,并且有几个限制.我对如何以良好的方式处理 DataIntegrityViolationException 表示怀疑.我想知道是否有一种方法可以将异常与属性文件中设置的消息进行映射,因为在约束验证中是可能的.我可以以任何方式自动处理它还是必须在每个控制器中捕获此异常?

I need to show custom messages in my Spring 3.0 application. I have a database with Hibernate and there are several constraints. I have doubts in how DataIntegrityViolationException should be handled in a good way. I wonder if there is a way to map the exception with a message set in a properties file, as it is possible in Constraints validation. Could I handle it automatically in any way or I have to catch this exception in each controller?

推荐答案

在违反约束的情况下显示用户友好消息的问题是当 Hibernate 的 ConstraintViolationException翻译成 Spring 的 DataIntegrityViolationException.

The problem with showing user-friendly messages in the case of constraint violation is that the constraint name is lost when Hibernate's ConstraintViolationException is being translated into Spring's DataIntegrityViolationException.

但是,您可以自定义此翻译逻辑.如果你使用 LocalSessionFactoryBean 来访问 Hibernate,你可以为它提供一个自定义的 SQLExceptionTranslator(参见 LocalSessionFactoryBean.jdbcExceptionTranslator).此异常转换器可以将 ConstraintViolationException 转换为您自己的异常类,同时保留约束名称.

However, you can customize this translation logic. If you use LocalSessionFactoryBean to access Hibernate, you can supply it with a custom SQLExceptionTranslator (see LocalSessionFactoryBean.jdbcExceptionTranslator). This exception translator can translate a ConstraintViolationException into your own exception class, preserving the constraint name.

这篇关于如何在 Spring 中处理 DataIntegrityViolationException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-26 03:41