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?
Very basically, Bean Validation works by defining constraints to the fields of a class by annotating them with certain annotations.
The Bean Validation API is a Java specification which is used to apply constraints on object model via annotations. Here, we can validate a length, number, regular expression, etc. Apart from that, we can also provide custom validations. As Bean Validation API is just a specification, it requires an implementation.
@NotNull validates that the annotated property value is not null. @AssertTrue validates that the annotated property value is true.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With