2

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.

Slava Semushin
  • 14,904
  • 7
  • 53
  • 69
Mulgard
  • 9,877
  • 34
  • 129
  • 232

1 Answers1

2

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:

Community
  • 1
  • 1
Slava Semushin
  • 14,904
  • 7
  • 53
  • 69
  • Ok but what if really always only want to validate the form, not the database operations but i have to use the same object always? The project im working on right now is really huge and to find all lines in the code where i would have to disable the validation would take very long time. So is there a better way to only validate the form posts using spring? – Mulgard Jul 22 '16 at 15:53
  • You're disabling validation not for each entity but only once, in the hibernate configuration. Or, you have multiple hibernate configurations? – Slava Semushin Jul 22 '16 at 15:56