What is point of constraint validation @Null?

Arashsoft picture Arashsoft · Jun 21, 2017 · Viewed 8k times · Source

I was checking list of available constraints in javax.validation package and I noticed that there is an annotation @Null which force the field to be null.

I do not understand what is point of adding it to my field if I already know it should be null.

For example look at this class:

public class MyClass{

    @NotNull
    private String myString1;

    @Null
    private String myString2;

    // getter setters...
}

@NotNull completely makes sense. I do not expect myString1 to be null. but @Null makes myString2 useless. What is point of having a field which should always be null.

Answer

ThreeDots picture ThreeDots · Sep 1, 2018

You may want to use @Null in combination with "Validation Group" to validate the null constraint only in certain cases.

Good explanation and example on validation groups provided by Hibernate

You will define validation group as simple interface

public interface FirstSave {}

then use it in constraint

public class MyClass {

    @Null(groups = FirstSave.class)
    private LocalDate lastUpdate;
}

then if lastUpdate is not null, calling validator.validate(myClassInstance) will not produce constraint violation (Default group was used), but calling validator.validate(myClassInstance, FirstSave.class) will.

You also have the possibility to provide your own implementation on how to use the annotation, i.e. I've seen validation method being annotated with @Null where null returned by the method meant that everything is alright. In the background there was probably custom implementation on what to do if annotated method returned not null result, but I didn't go deep into the code...