Hibernate的浮点映射精度 [英] Float mapping precision with Hibernate

查看:96
本文介绍了Hibernate的浮点映射精度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将浮点数存储在MySQL数据库中,但是Hibernate的值与列中存储的值不同

I'm trying to store a float in a MySQL database but Hibernate gets a differente value than what is stored in the column,

在我的应用中,我计算:

In my app I calculate:

float subtotal = 160.5f;
float ammount = (float) (subtotal * 0.1f); // this way I get the 10%
receipt.setAmmount(ammount);
receipt.save();

如果我记录了该数量,我将得到如下信息:

If I log that ammount I get something like this:

19/04/2013 10:17:20 [INFO] ServiceImpl: Added ammount x $16.05

我在mysql数据库中的 ammount 列为 FLOAT UNSIGNED ,当我执行选择时,我获得了16.05作为值,但是后来,当我使用Hibernate获取该对象时,ammount字段为16.049999237060547.

My column ammount in the mysql db is FLOAT UNSIGNED and when I do a select I obtain 16.05 as the value but later, when I fetch that object with Hibernate the ammount field is 16.049999237060547.

我的hbm列如下:

<property name="ammount" type="float"></property>

我在此处

I was reading here and here that is recommended to use BigDecimal in Java instead of Float or Double for money, but I can't get what data type should I use in my database or how to config Hibernate to use that datatype, thanks!

推荐答案

对于DECIMAL和NUMERIC类型,建议的Java映射是java.math.BigDecimal.java.math.BigDecimal类型提供数学允许添加,减去BigDecimal类型的操作,与其他BigDecimal类型相乘并相除,并带有整数类型,以及浮点类型.

The recommended Java mapping for the DECIMAL and NUMERIC types is java.math.BigDecimal. The java.math.BigDecimal type provides math operations to allow BigDecimal types to be added, subtracted, multiplied, and divided with other BigDecimal types, with integer types, and with floating point types.

建议检索DECIMAL和NUMERIC值的方法是ResultSet.getBigDecimal.JDBC还允许以下列方式访问这些SQL类型简单的字符串或字符数组.因此,Java程序员可以使用getString接收DECIMAL或NUMERIC结果.但是,这使得使用DECIMAL或NUMERIC表示货币值的常见情况

The method recommended for retrieving DECIMAL and NUMERIC values is ResultSet.getBigDecimal. JDBC also allows access to these SQL types as simple Strings or arrays of char. Thus, Java programmers can use getString to receive a DECIMAL or NUMERIC result. However, this makes the common case where DECIMAL or NUMERIC are used for currency values

请在此处

这篇关于Hibernate的浮点映射精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆