栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在Hibernate Validator 4.1+中,@ NotNull,@ NotEmpty和@NotBlank有什么区别?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在Hibernate Validator 4.1+中,@ NotNull,@ NotEmpty和@NotBlank有什么区别?

@NotNull
:CharSequence,Collection,Map或Array对象 不为null ,但 可以 为空。
@NotEmpty
:CharSequence,Collection,Map或Array对象不为null, 并且size > 0
@NotBlank
:字符串不为null ,并且修剪后的长度大于零

为了帮助您理解,让我们研究一下如何定义和执行这些约束(我使用的是4.1版):

  1. @NotNull
    约束被定义为:
    @Constraint(validatedBy = {NotNullValidator.class})

此类的

isValid
方法定义为:

    public boolean isValid(Object object, ConstraintValidatorContext constraintValidatorContext) { return object != null;  }
  1. @NotEmpty
    约束被定义为:
    @NotNull

    @Size(min = 1)

因此,此约束 使用

@NotNull
上面的约束, 并且
@Size
其定义因对象而异,但应该是自说明的。

  1. 最后,
    @NotBlank
    约束定义为:
    @NotNull

    @Constraint(validatedBy = {NotBlankValidator.class})

因此,此约束还使用了

@NotNull
约束,但也约束了NotBlankValidator类。此类的
isValid
方法定义为:

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

有趣的是,如果字符串为null,则此方法返回true,但仅当修剪后的字符串的长度为0时,此方法才返回false。如果为null,则返回true是可以的,因为正如我提到的,

@NotEmpty
定义也需要
@NotNull

这里有一些例子:

  1. 字符串名称= null;

    @NotNull
    :错误
    @NotEmpty
    :错误
    @NotBlank
    :错误

  2. 字符串名称=“”;

    @NotNull

    @NotEmpty
    :假
    @NotBlank
    :假

  3. 字符串名称=“”;

    @NotNull
    true
    @NotEmpty
    true
    @NotBlank
    :false

  4. 字符串名称=“好答案!”;

    @NotNull
    true
    @NotEmpty
    true
    @NotBlank
    true



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/417497.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号