我想做一些域验证。在我的对象中有一个整数。
现在我的问题是:如果我写
@Min(SEQ_MIN_VALUE)
@Max(SEQ_MAX_VALUE)
private Integer sequence;
和
@Size(min = 1, max = NAME_MAX_LENGTH)
private Integer sequence;
如果它是一个整数,那么哪一个更适合域验证?
有人能给我解释一下它们之间的区别吗?
谢谢。
发布于 2012-06-25 21:12:30
@Min
和@Max
用于验证数值字段,这些字段可以是String
(表示数字)、int
、short
、byte
等,以及它们各自的原语包装器。
@Size
用于检查字段的长度约束。
根据文档,@Size
支持String
、Collection
、Map
和arrays
,而@Min
和@Max
支持原语及其包装器。请参阅documentation。
发布于 2012-06-25 20:33:40
package com.mycompany;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
public class Car {
@NotNull
private String manufacturer;
@NotNull
@Size(min = 2, max = 14)
private String licensePlate;
@Min(2)
private int seatCount;
public Car(String manufacturer, String licencePlate, int seatCount) {
this.manufacturer = manufacturer;
this.licensePlate = licencePlate;
this.seatCount = seatCount;
}
//getters and setters ...
}
@NotNull
、@Size
和@Min
是所谓的约束注释,我们使用它们来声明约束,这些约束将应用于Car实例的字段:
manufacturer
不应为空
licensePlate
不能为空,并且长度必须在2到14个字符之间
seatCount
应至少为2。
发布于 2021-02-01 20:06:52
从documentation我得到的印象是,在您的示例中,它的目的是使用:
@Range(min= SEQ_MIN_VALUE, max= SEQ_MAX_VALUE)
检查带注解的值是否介于(包括)指定的最小值和最大值之间。支持的数据类型:
BigDecimal、BigInteger、CharSequence、byte、short、int、long和基本类型各自的包装器
https://stackoverflow.com/questions/11189398
复制相似问题