Search code examples
hibernatespring-mvcbean-validationhibernate-validator

Spring Form Validation validates database insert?


I want to use Spring Validation with Annotations to validate my form data. So i have the following object for example:

@Entity
@ComponentScan
public class Category {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private long id;

    @NotEmpty
    private String type;

    ...
}

As you can see here i used @NotEmpty on the type String. I want to use this only to validate my form. It should not be validating for database inserts.

So when i do:

@RequestMapping(value = "/myForm", method = RequestMethod.POST)
public String categoryPOST(HttpServletRequest request, Model model, @Valid Category category, BindingResult bindingResult) {
    if (bindingResult.hasErrors()) {
        return "form";
    }

    return "redirect:/results";
}

It is working as i want it to work. But when i have to create a dummy object:

Category category = new Category();

and i perform a save on that empty object:

this.category_repository.save(category);

I get the error (only important part of it):

Caused by: javax.validation.ConstraintViolationException: Validation failed for classes [my.project.jpa.entity.Category] during persist time for groups [javax.validation.groups.Default, ]
List of constraint violations:[
    ConstraintViolationImpl{interpolatedMessage='darf nicht leer sein', propertyPath=type, rootBeanClass=class my.project.jpa.entity.Category, messageTemplate='{org.hibernate.validator.constraints.NotEmpty.message}'}
]

And that is not what i want. I want to use the annotation for form validation but i do not want the validation to get performed on database operations.

is that somehow possible?

Additional information

I had the same result using:

javax.validation.constraints.NotNull;

Annotation.


Solution

  • Yes, it's possible.

    The first option is to use different classes for a form object (DTO) and entity.

    The second option is to configure Hibernate and disable validation before saving. Because this question already answered couple of times, I will provide links to them: