Round to 2 decimal places in hibernate query language

跟風遠走 提交于 2019-12-22 11:29:00

问题


Hi can someone help me how to round to 2 decimal places in hql?
I can't find anything online. Below is my query:

Select p.amount as amt,p.desc from pay p, register r where r.type=?1 and r.code=?2;

I would be glad if someone can help on this.

Technology used: hibernate, spring, java, primefaces 4.0, oracle database


回答1:


I have struggled with this a lot an finally found the following solution:

If you want to be more DB independent and specifically want to support Postgres or Oracle DB you can use the floor function for rounding which is pretty generic and does not leave much room for different implementations, meaning this will probably work with all databases (tested with Postgres and MySQL).

The snippet performs rounding to 2 digits and rounds by the absolute value. You can easily adapt this to your needs.

Regard the division by 100 using 100.0. This will insure that you always get a double as a result which is particularly important if you build a sum over the rounded values.

floor(abs(value) * 100 + 0.5)/100.0 * sign(value)



回答2:


use FORMAT function on property to 2 decimal point

Select FORMAT(p.amount,2) as amt,p.desc from pay p, register r where r.type=?1 and r.code=?2;

alternatively you can specify the same in mapping file as well like below

 <property name="amount">
        <column name="amount" scale="15" precision="3" sql-type="number(15,2)"/>
    </property>



回答3:


This worked for me

cast(value as decimal(9,2))


来源:https://stackoverflow.com/questions/23369306/round-to-2-decimal-places-in-hibernate-query-language

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!