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?
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)