为什么 bean 验证最小/最大约束不支持 double 类型?
有人可以向我解释一下为什么 JPA 支持 double 类型作为字段类型,但 bean 验证约束在 javax.validation.constraints 中(即 @Min/@Max) 不支持吗? 我知道文档说这是由于舍入错误造成的,但如果我选择字段类型为 double,我已经承认我不太关心显式精度。
我遇到这种困境的场景如下:我有一个代表地球表面上的一个点的实体。如果精度在几厘米以内就可以了。它看起来像这样:
@Entity
public class Point {
/**
* The longitude in radians.
*/
@Min(-Math.Pi)
@Max(Math.Pi)
double longitude;
/**
* The latitude in radians.
*/
@Min(-Math.Pi / 2)
@Max(Math.Pi / 2)
double latitude;
}
不幸的是,这不起作用,因为注释不支持 double 类型。但使用 BigDecimal 并不是真正的选择,因为我有一些涉及多个点的大量计算,但仍然需要相当快的速度。我通过定义一个与 double 一起使用的自定义约束检查来解决这个问题,但不知何故,我认为整个故事中我遗漏了一些东西。那么,我错过了什么?
Could somebody please explain to me why the JPA supports the double
type as a field type, but the bean validation constaints in javax.validation.constraints
(i.e. @Min/@Max) do not support it?
I know documentation says this is due to rounding errors, but if I choose the field type to be double
I already admit that I don't care that much about the explicit precision.
The scenario I ran into this dilemma is the following: I have an Entity that represents a point on the earth's surface. If the precision is within a few centimeters it's fine. It looks something like this:
@Entity
public class Point {
/**
* The longitude in radians.
*/
@Min(-Math.Pi)
@Max(Math.Pi)
double longitude;
/**
* The latitude in radians.
*/
@Min(-Math.Pi / 2)
@Max(Math.Pi / 2)
double latitude;
}
Unfortunately this does not work, because the annotations do not support the double type. But using BigDecimal
instead is not really an option, because I have some extensive computation with multiple points going on that still needs to be reasonably fast. I worked around it by defining a custom constraint check that does work with double
s, but somehow I think there is something I'm missing in the whole story. So, what am I missing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用@DecimalMin注释。
您将需要传递一个文字字符串值,因为属性
value
必须是常量(String.valueOf(- Math.PI))不起作用。它用于验证 Double 属性。
Use the
@DecimalMin
annotation.You will need to pass a literal String value, because the attrubute
value
must be constant (String.valueOf(- Math.PI)) doesn't work.It works to validate Double attributes.
这是因为四舍五入。但并不是因为双精度数可能不足以正确地表达您想要的数字。更重要的是,注释值(
Min
和Max
)是long类型,因此它不能表达任何带小数位的数字。另一方面,您不能使用 double 来精确表达 long 可以表达的所有数字。因此 API 设计者必须决定采用两种方式之一(长或双)
It is because of rounding. But not because of the problem that a double is may not correct enough to express the number you want. It is more that the annotation value (of
Min
andMax
) is of type long, so it can not express any number with decimal places. On the other hand you can not use a double to express exact all numbers that a long can express.So the API designers had to decide for one of the two ways (long or double)