如何在JPQL语句中使用typcasting? [英] How can I use typcasting inside a JPQL statement?
问题描述
我在数据库中有两个 Integer
列(derby和db2)。我需要在 JPQL
中将它们相互分开。
I have two Integer
columns in the database (derby and db2). I need to divide them with each other inside a JPQL
.
两列的类型都是整数
如果余数是十进制数,则返回零,例如 0.25
变为 0
等等,这是可以理解的所以因为type是int。
Both columns being of type Integer
return zero if remainder is a decimal number e.g 0.25
becomes 0
etc and understandably so since type is int.
在 SQL
我可以这样做
从Sometable中选择CAST(column1 as decimal(6,2))/ CAST(column2 as decimal(6,2));
但是什么是 JPQL
等价物。
一个选项可能是(我还没有尝试过)是在实体返回Decimal类型并在那里进行计算并将其传递给 JPQL的
但我宁愿让 @Transient
方法 SQL
这样做。
One option might be (I have not tried yet) is to have a @Transient
method in the entity returning the Decimal type and doing this calculation there and pass that to JPQL
but I would rather let SQL
do this work.
Mysql不需要在数据库级别进行转换。所以不同RDBMS的行为是不同的,这很好。但是JPQL应该如何处理需要使用本机查询来知道此操作需要转换为十进制。
Mysql does not require casting at database level . So Behaviour for different RDBMS is different which is fine . But what should JPQL do with out needing to use a native query to know that cast to decimal is needed for this operation.
添加方言< property name =openjpa.jdbc.DBDictionaryvalue =derby/>
也没有修复它。
Adding dialect <property name="openjpa.jdbc.DBDictionary" value="derby"/>
did not fix it either.
请请注意它是JPA1
推荐答案
您基本上有三种选择。
- 使用postload并让java执行此操作。
- 使用第三个类并在JPQL
的Select语句中使用New Operator来调用构造函数并且在调用内部你可以管理将传递给SQL的
数据类型,但是你将得到多于一个
种类的对象,这很好,只需从右边的
数组索引获得正确的一个。更多关于这个这里。 - 第三次使用像Idanmo这样的原生查询。
这篇关于如何在JPQL语句中使用typcasting?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!