Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA @Size annotation for BigDecimal

How do I use the @Size annotation for MySQL DECIMAL(x,y) columns?

I'm using BigDecimal, but when I try to include the @Size max it doesn't work. Here is my code:

@Size(max = 7,2)
@Column(name = "weight")
private BigDecimal weight;
like image 768
ThreaT Avatar asked Jan 03 '14 16:01

ThreaT


People also ask

Which annotation is default annotation in JPA?

The @Basic annotation has two attributes, optional and fetch. Let's take a closer look at each one. The optional attribute is a boolean parameter that defines whether the marked field or property allows null. It defaults to true.

How accurate is BigDecimal?

BigDecimal precision is de facto unlimited since it is based on an int array of arbitrary length. Though operations with double are much faster than with BigDecimal this data type should never be used for precise values, such as currency.

What is the difference between double and BigDecimal in Java?

A BigDecimal is an exact way of representing numbers. A Double has a certain precision. Working with doubles of various magnitudes (say d1=1000.0 and d2=0.001 ) could result in the 0.001 being dropped altogether when summing as the difference in magnitude is so large. With BigDecimal this would not happen.


1 Answers

You could use the Hibernate Validator directly, and annotate your field with @Digits like so:

@Digits(integer=5, fraction=2)
@Column(name = "weight")
private BigDecimal weight;
like image 60
mavroprovato Avatar answered Oct 01 '22 07:10

mavroprovato