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
.
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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…