Codementor Events

Resolving ConstraintViolationException in Spring JPA / JPA

Published Nov 20, 2017Last updated Nov 07, 2022

About me

Java developer.

Why I wanted to learn Spring JPA / JPA

project need.😃

How I approached learning Spring JPA / JPA

Documentation and examining existing code.

Challenges I faced

Most of spring JPA documentation available on spring.io site is more then sufficient to start working on spring jpa project. However spring jpa uses java jpa to perform operations.
CHALLENGE / PROBLEM faced: While trying to perform a simple 'Save' operation for an entity I started facing an error 'javax.validation.ConstraintViolationException'. It had huge spring jpa/ jpa stack trace but never pointed out the error or the field causing the error. They certainly need to improve logging in this case 😉.
I had complex Entity with multiple child references involving multiple tables. Each entity had many fields and it was not possible to verify the value of each field being tried to save. I was not sure what was wrong since the 'Save' operation was working fine for certain data cases and was throwing error in other.

SOLUTION: After googling for some time found out ,that we need to fill the gaps i.e we need to validate the entity being saved and log the validation error our selves in the code before saving the object.

So in order to get the field / exact issue I modified below code (off course for debugging purpose 😉

public void performSave(Object ObjectToSave) throws exception {
   daoObject.saveAndFlush(ObjectToSave);
 }

TO

public void performSave(Object ObjectToSave) throws exception {
    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();

    Set<ConstraintViolation<ObjectToSave>> constraintViolations = validator.validate(ObjectToSave);

    if (constraintViolations.size() > 0 ) {
      logger.info("VIOLATION OCCURED");
    for (ConstraintViolation<ObjectToSave> contraints : constraintViolations) {
    logger.info(contraints.getRootBeanClass().getSimpleName()+
        "." + contraints.getPropertyPath() + " " + contraints.getMessage());
      }
    }
    daoObject.saveAndFlush(ObjectToSave);
  }

Now called the method with the same data and Whoa ! 😃 I got the error. There was one field for which DB constraint was NotNull but was coming as null from UI . 😃. Fixed and am able to save the object. Cheers.

Key takeaways

1.) Not always your code is wrong 😉 Data could also be the issue sometime.
2.) Better debugging / logging is always going to help.

Tips and advice

Spring JPA helps in reducing boilerplate code. Queries are generated dynamically just by writing the field names in required format. i.e findByFirstName or findByFirstNameOrderbyLastName etc.

Final thoughts and next steps

Discover and read more posts from Amol Bhujbal
get started