您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

@NotNull:CharSequence,Collection,Map或Array对象 ,但 可以 为空。@NotEmpty:CharSequence,Collection,Map或Array对象不为null, 。@NotBlank:字符串不为null 。

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

@Constraint(validatedBy = {NotNullValidator.class})

此类的isValid方法定义为:

    public boolean isValid(Object object, ConstraintValidatorContext constraintValidatorContext) {
 return object != null;  
}
@NotNull

@Size(min = 1)

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

@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

这里有一些例子:

字符串名称= null; @NotNull错误@NotEmpty错误@NotBlank错误

字符串名称=“”; @NotNull@NotEmpty:假@NotBlank:假

字符串名称=“”; @NotNull@NotEmpty@NotBlank:false

字符串名称=“好答案!”;@NotNull@NotEmpty@NotBlank

其他 2022/1/1 18:14:06 有548人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶