我正在尝试在我的实体上执行JPA命名查询,但它显示语法错误。谁能告诉我我的命名查询有什么问题?
@Repository
public interface CollegeRepository extends CrudRepository<CollegeEntity, Integer> {
@Query("SELECT c FROM(SELECT *,(((acos(sin((:latitude * pi()/180)) * sin((latitude*pi()/180))+cos((:latitude * pi()/180)) * cos((latitude*pi()/180)) * cos(((:longitude - longitude)*pi()/180))))*180/pi())*60*1.1515*1.609344) as distance FROM college) t WHERE distance <= 30")
List<CollegeEntity> getCollegeByLocation(@Param("latitude") Double latitude, @Param("longitude") Double longitude, @Param("distance") Integer distance);
}
执行上述查询后,这是错误。
Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: ( near line 1, column 14 [SELECT c FROM(SELECT *,(((acos(sin((:latitude * pi()/180)) * sin((latitude*pi()/180))+cos((:latitude * pi()/180)) * cos((latitude*pi()/180)) * cos(((:longitude - longitude)*pi()/180))))*180/pi())*60*1.1515*1.609344) as distance FROM college) t WHERE distance <= :distance]
当我在MySQL终端中执行以下本机查询时,那么工作正常。
mysql> SELECT * FROM(SELECT *,(((acos(sin((0.0 * pi()/180)) * sin((latitude*pi()/180))+cos((0.0 * pi()/180)) * cos((latitude*pi()/180)) * cos(((0.0 - longitude)*pi()/180))))*180/pi())*60*1.1515*1.609344) as distance FROM college) t WHERE distance <= 30;
Empty set (0.08 sec)
答案 0 :(得分:1)
您的查询似乎不是正确的JPQL语法,因为JPA中没有acos
,pi
,sin
,cod
函数,您的查询看起来像一个原生查询,为了解决您的问题,您有两个选择:
nativeQuery = true
属性@Query(nativeQuery = true, value="SELECT * FROM(...")
,请注意*
您的查询中没有别名c
。您可以使用:
@Query(value = "SELECT * FROM(SELECT *,"
+ "(((acos(sin((0.0 * pi()/180)) * sin((latitude*pi()/180)) + "
+ "cos((0.0 * pi()/180)) * cos((latitude*pi()/180)) * "
+ "cos(((0.0 - longitude)*pi()/180))))*180/pi()) * "
+ "60*1.1515*1.609344) as distance FROM college) t WHERE distance <= 30;",
nativeQuery = true)
在你的情况下,我强烈建议第二种选择。