开发者

Why do bean validation Min/Max constraints not support the double type?

开发者 https://www.devze.com 2023-04-04 18:00 出处:网络
Could somebody plea开发者_运维百科se 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 supp

Could somebody plea开发者_运维百科se 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 doubles, but somehow I think there is something I'm missing in the whole story. So, what am I missing?


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.

@DecimalMin(value = "0.01", message = "Your message...")
private Double longitude;


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 and Max) 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)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号