问题描述
我将Oracle 11g中的这个列映射为NUMBER(21,20),它被映射到Hibernate中: @Column(name =PESO,precision = 21,scale = 20,nullable = false)
public BigDecimal getWeight(){
return weight;
}
对于列的值为0.493的特定记录,我得到一个BigDecimal的值为0.49299999999。
似乎某个地方由于(也许)到Double或Float转换会导致精度的损失,但是我无法通过简单的单元测试来跟踪它。
Double d = new Double(0.493);
System.out.println((d));
使用Float,BigDecimal和各种构造函数的代码的任何变体都提供了相同的结果:0.493 ...
任何提示如何映射列以避免这样的问题?
我使用Hibernate 3.5.6,使用JPA注释和Hibernate API(即Session而不是EntityManager)
p>这是从 double
中初始化 BigDecimal
的结果:
System.out.println(String.format(%21.20f,new BigDecimal(0.493));
//打印0,49299999999999999378
所以,当这种方式初始化的 BigDecimal
保存在数据库中产生一个不准确的值,稍后将被正确加载。
如果 BigDecimal
由字符串初始化,或者如果值为直接在Java中设置一切正常。
I have this column in my Oracle 11g mapped as NUMBER (21,20), which is mapped in Hibernate as:
@Column(name = "PESO", precision = 21, scale = 20, nullable = false)
public BigDecimal getWeight() {
return weight;
}
For a particular record for which the value of the column is 0.493 I get a BigDecimal whose value is 0.49299999999.It seems that somewhere there is a loss of precision due (maybe) to a Double or Float conversion, but I couldn't track it down with a simple unit test like this:
Double d = new Double("0.493");
System.out.println((d));
Any variant of that code, using Float, BigDecimal and various constructors gives the same result: "0.493"...Any hint on how should I map the column to avoid such issues?I'm using Hibernate 3.5.6, with JPA annotations and Hibernate API (that is Session and not EntityManager)
It's a result of initializing BigDecimal
from double
:
System.out.println(String.format("%21.20f", new BigDecimal(0.493));
// Prints 0,49299999999999999378
So, when BigDecimal
initialized this way is saved in the database, it produces an inaccurate value, which is correctly loaded later.
If BigDecimal
is initialized by string or if the value is set directly in Java everything works fine.
这篇关于当将数字(22,21)映射到BigDecimal时,Hibernate在结果中的精度丢失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!