Java 如何在休眠时指定 Double 的精度?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4078559/
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-14 11:21:47  来源:igfitidea点击:

How to specify Double's precision on hibernate?

javahibernatejpa

提问by artaxerxe

I try to create a table from hibernate annotations. I need to have a column of Double type, with the length specified like : (10,2). So SQL syntax show like:

我尝试从休眠注释创建一个表。我需要有一个 Double 类型的列,其长度指定为:(10,2)。所以 SQL 语法显示如下:

... DOUBLE(10,2) ....

I have tried to do that:

我试图这样做:

@Column(length = 10, precision = 2) ...

but when i look at my created table, it is not specified the length for Double column. Does hibernate has solution for that or is it necessary to alter table configuration by hand?

但是当我查看我创建的表时,它没有指定双列的长度。Hibernate 是否有解决方案,或者是否有必要手动更改表配置?

Thanks!

谢谢!

采纳答案by Pascal Thivent

The lengthelement of the Column annotation applies only if a string-valued column is used. In your case, you should use the precisionand the scaleelements.

lengthColumn 注释的元素仅在使用字符串值列时才适用。在您的情况下,您应该使用precisionscale元素。

@Column(precision=10, scale=2)

Here is what the specification writes about them:

以下是规范中关于它们的内容:

  • int- precision- (Optional) The precision for a decimal (exact numeric) column. (Applies only if a decimal column is used.)
  • int- scale- (Optional) The scale for a decimal (exact numeric) column. (Applies only if a decimal column is used.)
  • int- precision- (可选)小数(精确数字)列的精度。(仅在使用小数列时适用。)
  • int- scale- (可选)小数(精确数字)列的小数位数。(仅在使用小数列时适用。)

References

参考

  • JPA 1.0 Specification
    • Section 9.1.5 "Column Annotation"
  • JPA 1.0 规范
    • 第 9.1.5 节“列注释”

回答by Kris

@Column(name="Price", columnDefinition="Decimal(10,2) default '100.00'")

Setting default values for columns in JPA

为 JPA 中的列设置默认值

回答by FearlessHyena

You can also use @Digitsfrom the hibernate validator API which implements the javax.validation Bean Validation standard

您还可以@Digits从实现 javax.validation Bean Validation 标准的 hibernate 验证器 API 中使用

@Digits(integer = 10 /*precision*/, fraction = 2 /*scale*/)

From the Javadocs

来自 Javadocs

The annotated element must be a number within accepted range Supported types are:

  • BigDecimal
  • BigInteger
  • CharSequence
  • BigInteger
  • byte, short, int, long, and their respective wrapper types

null elements are considered valid

带注释的元素必须是可接受范围内的数字支持的类型有:

  • 大十进制
  • 大整数
  • 字符序列
  • 大整数
  • byte、short、int、long 及其各自的包装器类型

null 元素被认为是有效的

回答by zeratul021

Use @Type(only in Hibernate):

使用@Type(仅在 Hibernate 中):

@Column(precision = 5, scale = 4)
@Type(type = "big_decimal")
private double similarity;

Will result in definition (PostgreSQL, Oracle):

将导致定义(PostgreSQL、Oracle):

similarity numeric(5, 4),
similarity number(5, 4)