Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
351 views
in Technique[技术] by (71.8m points)

java - In Hibernate Validator 4.1+, what is the difference between @NotNull, @NotEmpty, and @NotBlank?

I can't seem to be able to find a summary that distinguishes the difference between these three annotations.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

To help you understand, let's look into how these constraints are defined and carried out (I'm using version 4.1):

  1. The @NotNull constraint is defined as:

    @Constraint(validatedBy = {NotNullValidator.class})  
    

    This class has an isValid method defined as:

    public boolean isValid(Object object, ConstraintValidatorContext constraintValidatorContext) {
     return object != null;  
    }
    
  2. The @NotEmpty constraint is defined as:

    @NotNull  
    @Size(min = 1)    
    

    So this constraint uses the @NotNull constraint above, and @Size whose definition differs based on the object but should be self explanitory.

  3. Finally, the @NotBlank constraint is defined as:

    @NotNull  
    @Constraint(validatedBy = {NotBlankValidator.class})        
    

    So this constraint also uses the @NotNull constraint, but also constrains with the NotBlankValidator class. This class has an isValid method defined as:

    if ( charSequence == null ) {  //curious 
      return true;   
    }   
    return charSequence.toString().trim().length() > 0;  
    

    Interestingly, this method returns true if the string is null, but false if and only if the length of the trimmed string is 0. It's ok that it returns true if it's null because, as I mentioned, the @NotEmpty definition also requires @NotNull.

Here are a few examples:

  1. String name = null;
    @NotNull: false
    @NotEmpty: false
    @NotBlank: false

  2. String name = "";
    @NotNull: true
    @NotEmpty: false
    @NotBlank: false

  3. String name = " ";
    @NotNull: true
    @NotEmpty: true
    @NotBlank: false

  4. String name = "Great answer!";
    @NotNull: true
    @NotEmpty: true
    @NotBlank: true


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...