@NotEmpty、@NotNull、@NotBlank的源码注释、区别、举例

网上搜索总结如下,
@NotEmpty、@NotNull、@NotBlank的区别
1 @NotEmpty :不能为null,且Size>0
2 @NotNull:不能为null,但可以为empty,没有Size的约束
3 @NotBlank:只用于String,不能为null且trim()之后size>0


不够具体,不权威,直接上源码注释!

@NotEmpty

/** 
* Asserts that the annotated string, collection, map or array is not {@code null} or empty. 
* 
* @author Emmanuel Bernard 
* @author Hardy Ferentschik 
*/

断言,带注解的String,collection,map或数组不能为null,也不能为空。
也就是说,有@NotEmpty注解的String、Collection、Map、数组是不能为null或长度为0

踩坑
@NotEmpty(message = "id不能为null或空")
pirvate Long id;   
错!这是基础类型的包装类、除了以上4种类型都不能使用@NotEmpty

@NotNull(message = "id不能为null或空")
private Long id; 
正确

@NotBlank

/** 
* Validate that the annotated string is not {@code null} or empty. 
* The difference to {@code NotEmpty} is that trailing whitespaces are getting ignored. 
* 
* @author Hardy Ferentschik 
*/

验证注释的String不是null或空的,与@NotEmpty的区别在于,尾部空格被忽略,也就是说,纯空格的String也是不符合规则的,此注解只能用于验证String类型

@NotNull

/** 
* The annotated element must not be {@code null}. 
* Accepts any type. 
* 
* @author Emmanuel Bernard 
*/

带注释的元素不能为null。接受任何类型。完美!

应用场景

数据库表student_message
实体类时Student
属性有

//id不能为null
@NotNull
private int id;

//姓名不能为null,也不能为“  ”
@NotEmpty
private String name;

//爱好不能为null,但可以为“  ”
@NotNull
private String favorite;

//家庭住址不能为null,只能填String,trim()去掉尾部空格后,
//字符串个数大于0.类别:(必填项)
@NotBlank
private String address;
  • 3
    点赞
  • 32
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值