'Hibernate validation: Skip Constraint violation in specific situations(api calls)

I have an object User and as part of validation I have provided something like below:

import javax.validation.constraints.NotBlank;

public class User {

    private String id;

    @NotBlank
    private String name;

    @NotBlank
    private String email;

    private String archiveDate;
}

in the middle, the email is changed as a required field and some of already existing users doesn't have email value at all. For these users we have options

  1. to fill data from the front end
  2. we can delete that user(soft delete => setting archive date field with current date).

In both cases, we are doing it by patch/update. Here the problem with 2nd option is it won't allow to set archiveDate fields and throws constraintviolationexception.

Is it possible to skip this constraint validation in a specific(API call) situation? how to handle it.



Solution 1:[1]

Yes! You need to use ValidationGroups. That allows you to selectively activate certain bean validation constraints.

Here's a quick tutorial on how to create a Validation Group: https://www.baeldung.com/javax-validation-groups

public interface ApiCallGroup {
}

public class User {
...
    @NotBlank( groups = ApiCallGroup.class )
    private String email;
...
}

You can then:

@Inject private Validator validator;

...

  validator.validate(apiCall, ApiCallGroup.class);

and run a specific group before persistence, and/OR you can configure Hibernate to run a group of annotations. https://docs.jboss.org/hibernate/validator/5.1/reference/en-US/html/chapter-groups.html

Other reference to validator API: https://docs.oracle.com/javaee/7/api/javax/validation/Validator.html#validate-T-java.lang.Class...-

Hopefully that helps. If you can post a little more of your code we could probably figure out how to call the validator, but if this was useful, don't forget to upvote or accept this as an answer.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jonathan S. Fisher