Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is point of constraint validation @Null?

Tags:

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.

like image 825
Arashsoft Avatar asked Jun 21 '17 18:06

Arashsoft


People also ask

What is the difference between not null and not blank?

@NotNull : The CharSequence, Collection, Map or Array object is not null, but can be empty. @NotEmpty : The CharSequence, Collection, Map or Array object is not null and size > 0. @NotBlank : The string is not null and the trimmed length is greater than zero.

How do you validate constraints?

Constraint validation process Constraint validation is done through the Constraint Validation API either on a single form element or at the form level, on the <form> element itself.

What is @NotNull annotation in spring boot?

Overview. NullPointerExceptions are a common problem. One way we can protect our code is to add annotations such as @NotNull to our method parameters. By using @NotNull, we indicate that we must never call our method with a null if we want to avoid an exception. However, by itself, that's not enough.

What does @NotNull annotation Bean in Bean property?

@NotNull validates that the annotated property value is not null. @AssertTrue validates that the annotated property value is true.


1 Answers

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...

like image 184
ThreeDots Avatar answered Oct 07 '22 18:10

ThreeDots