Search code examples
springhibernateexceptionspring-datahibernate-validator

Spring data and hibernate - model validations - exception translation


I use spring-data and hibernate. Now I would like to apply some validation to my model. In most cases I would like to apply simple validation like null-checking etc. But in some cases I would like to apply more strict validation, such as email-validation. I found very useful feature in Hibernate validator - the @Email annotation. It works very well but here is the problem:

If i try to save a model with null value, then the following exception is thrown:

org.springframework.dao.DataIntegrityViolationException

But if I try to save a model with non-null but non-email value (let's say asdfgh), then the following exception is thrown:

javax.validation.ConstraintViolationException

I would love to see only one type of exception in both cases, because in both cases the model didn't pass the validation and I would like just to worry about only one exception type in my exception-handling code.

I tried to add PersistenceExceptionTranslationPostProcessor to my bean configuration, but it looks like it does not change anything.

Do you have an idea how to "unify" this exceptions?

Model:

@Entity
public class ValidationModel {
    ...

    @Email
    @Column(nullable = false)
    private String email;

    ...
}

Repository:

public interface ValidationModelRepository extends JpaRepository<ValidationModel, Long> {
}

Solution

  • @Column(nullable = false) is not a validation check. It's a JPA constraint.

    To validate that a value is not null, use @NotNull.