Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 doubles, but somehow I think there is something I'm missing in the whole story. So, what am I missing?

like image 339
Manuel Leuenberger Avatar asked Sep 14 '11 20:09

Manuel Leuenberger


People also ask

How does Bean Validation work?

Very basically, Bean Validation works by defining constraints to the fields of a class by annotating them with certain annotations.

How does Java Bean Validation work?

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.

What does javax validation constraints NotNull do?

@NotNull validates that the annotated property value is not null. @AssertTrue validates that the annotated property value is true.


1 Answers

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; 
like image 68
Rodrigo Araujo Avatar answered Sep 17 '22 09:09

Rodrigo Araujo