对Spring JPA命名查询的本机SQL查询

时间:2015-02-11 07:30:14

标签: java sql hibernate jpa jpql

我有以下查询。

SELECT zip, primary_city, latitude, longitude,
      111.045* DEGREES(ACOS(COS(RADIANS(latpoint))
                 * COS(RADIANS(latitude))
                 * COS(RADIANS(longpoint) - RADIANS(longitude))
                 + SIN(RADIANS(latpoint))
                 * SIN(RADIANS(latitude)))) AS distance_in_km
 FROM zip
 JOIN (
     SELECT  42.81  AS latpoint,  -70.81 AS longpoint
   ) AS p ON 1=1
 ORDER BY distance_in_km
 LIMIT 15

当我在sql编辑器中执行上述查询时,我从zip表中获取zip,primary_city,latitude,longitude,distance_in_km。

我需要在我的JPA存储库中使用相同的内容。我尝试使用命名查询,但它显示验证失败的异常。也在我的实体类zip.java中只有 zip,primary_city,纬度,经度(四个属性)。我需要决定如何捕获来自resultset的distance_in_km 请帮助我如何在Spring JPA中实现相同的目标

1 个答案:

答案 0 :(得分:0)

  1. 首先,您需要设置nativeQuery标志,因为这不是JPQL查询。

  2. 当查询没有给出这样的参数时,SQL查询使用:latitude的命名参数。

  3. 您错过了查询第5行的“+”符号:

    +"*COS(RADIANS(longpoint) - RADIANS (height))"
    +" SIN (RADIANS (latpoint))"
    
  4. 应该是:

        +"*COS(RADIANS(longpoint) - RADIANS (height))"
        +" + SIN (RADIANS (latpoint))"
    
    1. JOIN条件不接受任何表格,所以我不确定你想要做什么加入。
    2. 您的查询应写为:

      SELECT 
          code,
          name,
          length,
          height, 
          111.045* DEGREES (ACOS(COS(RADIANS(latpoint)) * COS (RADIANS(length)) * COS(RADIANS(longpoint) - RADIANS (height)) + SIN (RADIANS (latpoint)) *SIN (RADIANS(length)))) As distance_in_km,
          latitude AS latpoint, 
          longitute AS longpoint
      FROM place
      ORDER BY distance_in_km
      LIMIT 5
      

      永远不要低估代码缩进的力量。其他一些开发人员可能需要维护此查询,因此请始终根据需要编写查询。