How can I use typcasting inside a JPQL statement?

守給你的承諾、 提交于 2019-12-05 06:03:20

You have basically three options.

  1. Use postload and let java do it .
  2. Use a third Class and use New Operator in Select statement of JPQL to call constructor and inside that calls you can manage the datatypes which will be passed to SQL but you will get more then one kind of objects back which is fine just get the right one from right array index.More on this here.
  3. Third use Native Query like Idanmo said.

That the division operator performs integer division on integer arguments is a feature. In MySQL you have to explicitly choose div for integer division and / for floating point division, whereas in JPQL the choice is made automatically just like in Java.

So I suggest:

select (column1 * 1.0) / column2 from Sometable;
idanmo

AFAIK there isn't a way to do this kind of cast in JPQL.

I suggest using JPA's native query execution which lets you run an SQL query like you would if you were using JDBC.

For instance:

Query query = em.createNativeQuery("select CAST(column1 as decimal(6,2))/CAST(column2 as decimal(6,2)) from Sometable");

Double result = (Double) query.getSingleResult();

or

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