简体   繁体   English

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

[英]Native SQL query to Spring JPA named query

I am having below query. 我在下面查询。

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

When I execute the above query in sql editor i am getting zip,primary_city, latitude, longitude ,distance_in_km from zip table. 当我在sql编辑器中执行上述查询时,我从zip表中获取zip,primary_city,纬度,经度,distance_in_km。

I need to use the same in my JPA repository.I tried using named query but it shows Validation failed exception.Also In my entity class zip.java having only zip, primary_city, latitude, longitude(four attributes).I need to decide how to capture distance_in_km which comes from resultset Kindly help me how to achieve the same in Spring JPA 我需要在JPA存储库中使用相同的代码。我尝试使用命名查询,但它显示了验证失败的异常。此外,在我的实体类zip.java中,它仅包含zip,primary_city,纬度,经度(四个属性)。捕获来自结果集的distance_in_km请帮助我如何在Spring JPA中实现相同

  1. First you need to set the nativeQuery flag, because this is not a JPQL query. 首先,您需要设置nativeQuery标志,因为这不是JPQL查询。

  2. The SQL query uses named parameters for :latitude , when there's no such parameter given to the query. 当没有给查询提供此类参数时,SQL查询将为:latitude使用命名参数。

  3. You missed the "+" sign on the 5th line of your query: 您错过了查询第5行上的“ +”号:

     +"*COS(RADIANS(longpoint) - RADIANS (height))" +" SIN (RADIANS (latpoint))" 

should be: 应该:

    +"*COS(RADIANS(longpoint) - RADIANS (height))"
    +" + SIN (RADIANS (latpoint))"
  1. The JOIN condition doesn't take any table, so I am not sure what you wanted to do JOIN with. JOIN条件不占用任何表,因此我不确定您要使用JOIN做什么。

You query should be written as: 您的查询应写为:

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

Never underestimate the power of code indentation. 永远不要低估代码缩进的力量。 Some other develop might have to maintain this query, so always write your queries as you want to find them. 其他一些开发人员可能必须维护该查询,因此请始终根据需要编写查询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM