Java BigDecimal 的 JPA @Size 注释

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20907923/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 05:14:52  来源:igfitidea点击:

JPA @Size annotation for BigDecimal

javamysqljpabean-validation

提问by ThreaT

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

如何使用@SizeMySQLDECIMAL(x,y)列的注释?

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

我正在使用BigDecimal,但是当我尝试包含@Sizemax它时它不起作用。这是我的代码:

@Size(max = 7,2)
@Column(name = "weight")
private BigDecimal weight;

采纳答案by mavroprovato

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

您可以直接使用 Hibernate Validator,并使用@Digits注释您的字段,如下所示:

@Digits(integer=5, fraction=2)
@Column(name = "weight")
private BigDecimal weight;

回答by zmf

@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.

如果你问你应该如何验证,你应该使用@Min 和@Max 批注或@DecimalMin 和@DecimalMax 批注。

@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.

@Size 是用于验证属性的注释,而不是用于定义其列。@Size 通常用于确保字符串或集合具有特定大小。

回答by borjab

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;