网上搜索总结如下,
@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;