How to handle DataIntegrityViolationException in Spring?

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.

Leave a Comment