JPA @Size annotation for BigDecimal
45,082
Solution 1
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;
Solution 2
See this answer
@Column(nullable= false, precision=7, scale=2) // Creates the database field with this size.
@Digits(integer=9, fraction=2) // Validates data when used as a form
private BigDecimal myField;
Solution 3
@Column(columnDefinition = "DECIMAL(7,2)")
If you're asking how you should validate, you should use the @Min and @Max annotations or the @DecimalMin and @DecimalMax annotations.
@Size is an annotation used to validate a property, not to define its column. @Size is typically used to assure that a string or a collection is of a certain size.
Author by
ThreaT
Updated on July 09, 2022Comments
-
ThreaT almost 2 years
How do I use the
@Size
annotation for MySQLDECIMAL(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;
-
ThreaT over 10 yearsSo how would I use
@Max
to validate aBigDecimal
with7,2
? -
ThreaT over 10 yearsWould it work with TopLink's
javax.persistence_1.0.0.0_1-0-2.jar
as well? -
zmf over 10 years@Threat when you say 'validate a BigDecimal with 7,2' ... can you clarify that a bit? When I read that I assume you're speaking about a BigDecimal with a specific scale and precision, which is different from a min and max value.
-
ThreaT over 10 yearsIn other words, my
BigDecimal
must conform to, for example,9999999,99
maximum. The same way that MySQL would validate it as far as I understand. -
mavroprovato over 10 yearsValidation is a separate API from JPA. So, there will be no error when you try to persist the entity through
persist()
for example, you have to do the validation yourself -
mavroprovato over 10 years@ThreaT,
DECIMAL(7,2)
means a total of 7 digits, 2 of which are after the decimal point. So the maximum value that it can hold is 99999,99 -
ThreaT over 10 yearsHow do I do the validation myself? Is there a link to Oracle's site where I could read more on that?
-
mavroprovato over 10 yearsWhat I meant is that validation should be done before you try to save to the database, at the view layer. See docs.oracle.com/javaee/6/tutorial/doc/gircz.html if you are using JSF, or here if you are using Spring docs.spring.io/spring/docs/3.2.x/spring-framework-reference/…
-
ThreaT over 10 yearsJava EE 7: docs.oracle.com/javaee/7/tutorial/doc/… Looks like
@DecimalMax
is the annotation to use? -
kensai over 6 yearsIt is throwing me SQL Error: 0, SQLState: 22003, ERROR: numeric field overflow. source is BigDecimal field. I tried to put over @Column(columnDefinition = "DECIMAL(8,8)"), so there is something more I need to discover.
-
Tony Wen over 3 yearsI think it should be @Column(nullable= false, precision=9, scale=2) and @Digits(integer=7, fraction=2)