问题描述
我需要在我的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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!