Hibernate在PostgreSQL上执行sum函数导致数据失真的问题
有一段通过Hibernate从PostgreSQL上进行sum统计的简单代码,但统计结果却导致数据失真,不知原因何在,求指教!
Java代码片段如下:
public List<Object> getSalesRanking( ) throws Exception{ StringBuilder sbHql = new StringBuilder(); sbHql.append("select dl.dishId, dl.dishName, sum(dl.counts) as t, sum(dl.price) as s from R311dishList dl ") .append(" where dl.dishName='松仁玉米'") .append(" group by dl.dishId, dl.dishName"); String hql = sbHql.toString(); SQLQuery query = sf.getCurrentSession().createSQLQuery(hql); query.addScalar("dishId", StandardBasicTypes.STRING); query.addScalar("dishName", StandardBasicTypes.STRING); query.addScalar("t", StandardBasicTypes.DOUBLE); query.addScalar("s", StandardBasicTypes.DOUBLE); List<Object> list = new ArrayList<Object>(); ScrollableResults rs = query.scroll(); while(rs.next()){ try{ Object[] obj = new Object[4]; obj[0] = rs.getString(0); obj[1] = rs.getString(1); obj[2] = rs.getDouble(2); obj[3] = rs.getDouble(3); list.add(obj); } catch(Exception ex){ String err = ex.toString(); throw ex; } } return list; }
对应的数据库表R311DishList中相关数据如下:
请注意,要统计的counts字段的数据分别是2.4/2.3/2.6,counts字段是double类型的,按道理sum(counts)后的结果应该是7.3,且通过SQL直接在数据库上执行的结果也确实是7.3,如下图:
可是,通过代码执行得到的结果却是7.299999999999999:
修改数据库中三条记录的counts值为其他值均正常,且偶尔调整三条记录的顺序后也能正常显示。不知何故??
=======================================================================
野文(Jasson Qian)
------------------------------------------------------
博客园:http://qguohog.cnblogs.com
CSDN:http://blog.csdn.net/sallay