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.
@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.
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.
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.
@NotNull validates that the annotated property value is not null. @AssertTrue validates that the annotated property value is true.
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With