何在NamedQuery中使用JPQL创建具有计算的瞬态属性的实

何在NamedQuery中使用JPQL创建具有计算的瞬态属性的实

本文介绍了如何在NamedQuery中使用JPQL创建具有计算的瞬态属性的实体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一条SQL语句:

SELECT x.SPEED, (6371 * acos(cos(radians(16.65555)))
                 * cos(radians(LATITUDE)) * cos(radians(LONGITUDE) - radians(54.55555))
                 + sin(radians(16.65555)) * sin(radians(LATITUDE))) AS dist
FROM MY_TABLE x
HAVING dist <= 50
ORDER BY dist

我该如何将其放入Java实体类中的NamedQuery中,以一种方式将计算出的值作为称为 distance 的瞬时属性设置到该实体中?

How can I put this into a NamedQuery within a Java entity class in a way that the calculated value is set into this entity as a transient attribute called distance?

暂时我已经尝试过了:

SELECT vsle,
       (:distance_unit * FUNC('acos', FUNC('cos', FUNC('radians', :latitude)) *
       FUNC('cos', FUNC('radians', vsle.geoPosition.latitude)) *
       FUNC('cos', FUNC('radians', vsle.geoPosition.longitude) - FUNC('radians', :longitude)) +
       FUNC('sin', FUNC('radians', :latitude)) * FUNC('sin', FUNC('radians', vsle.geoPosition.latitude)) ) )
AS distance
FROM VehicleStateLogEntity vsle
WHERE (distance <= :radius)

,但这失败,并出现java.lang.NullPointerException.似乎无法通过其分配的名称​​ distance 访问计算值.

but this fails with a java.lang.NullPointerException. It seems as if the calculated value cannot be accessed via its assigned name distance.

推荐答案

我找到了一种构建有效的JPQL的方法:

I found a way to build the JPQL valid:

SELECT vsle,
   (:distance_unit * FUNC('acos', FUNC('cos', FUNC('radians', :latitude)) *
   FUNC('cos', FUNC('radians', vsle.geoPosition.latitude)) *
   FUNC('cos', FUNC('radians', vsle.geoPosition.longitude) - FUNC('radians', :longitude)) +
   FUNC('sin', FUNC('radians', :latitude)) * FUNC('sin', FUNC('radians', vsle.geoPosition.latitude)) ) ) AS distance
FROM VehicleStateLogEntity vsle
WHERE ((:distance_unit * FUNC('acos', FUNC('cos', FUNC('radians', :latitude)) *
   FUNC('cos', FUNC('radians', vsle.geoPosition.latitude)) *
   FUNC('cos', FUNC('radians', vsle.geoPosition.longitude) - FUNC('radians', :longitude)) +
   FUNC('sin', FUNC('radians', :latitude)) * FUNC('sin', FUNC('radians', vsle.geoPosition.latitude)) ) )<= :radius)
ORDER BY distance

很奇怪,我无法在SELECT子句中访问别名 distance ,但可以在ORDER BY子句中访问.

It's weird that I can't access the alias distance in the SELECT-clause but I can in the ORDER BY-clause.

这篇关于如何在NamedQuery中使用JPQL创建具有计算的瞬态属性的实体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 03:36