JpaRepository本机查询未检测到参数

时间:2019-06-30 07:47:39

标签: hibernate spring-boot jpa spring-data-jpa

我正在尝试在SpringBoot应用程序中编写本机查询,以获取与任何给定坐标最接近的位置。以下是相同的JpaRepository:

declare module "rxjs" {
    interface Observable<T> {
      pipeIf(validExpression:boolean, truePipe:Array<UnaryFunction<T,T>>, falsePipe:Array<UnaryFunction<T,T>>): Observable<T>
    }
  }

  Observable.prototype.pipeIf = function(validExpression:boolean, truePipe:Array<OperatorFunction<any,any>>, falsePipe:Array<OperatorFunction<any,any>>):Observable<any>{
    return validExpression ? this.pipe.apply(this,truePipe) : this.pipe.apply(this, falsePipe)
  }

我面临的问题是,在查询字符串中未设置传递的纬度和经度。而是将它们替换为问号,如下所示:

@Repository
public interface OfferRepository extends JpaRepository<Offer, Long> {
    @Query(value = "SELECT *, MIN(6371000 * acos( cos( radians(:latitude) ) * cos( radians( dest.latitude ) ) * cos( radians( dest.longitude ) - radians(:longitude) ) + sin( radians(:latitude) ) * sin( radians( dest.latitude ) ))) as  distance FROM offer dest GROUP BY dest.id having MIN(distance)",
            nativeQuery = true)
    Tuple getClosestOffer(double latitude, double longitude);
}

我什至尝试使用带编号的参数,但结果相同。我在这里做错了什么?该如何解决?

1 个答案:

答案 0 :(得分:2)

您可以使用 @Param 批注使用命名参数

public interface OfferRepository extends JpaRepository<Offer, Long> {
    @Query(value = "SELECT *, MIN(6371000 * acos( cos( radians(:latitude) ) * cos( radians( dest.latitude ) ) * cos( radians( dest.longitude ) - radians(:longitude) ) + sin( radians(:latitude) ) * sin( radians( dest.latitude ) ))) as  distance FROM offer dest GROUP BY dest.id having MIN(distance)",
            nativeQuery = true)
    Tuple getClosestOffer(@Param("latitude") double latitude, @Param("longitude") double longitude);
}

或在您的jpql中使用索引参数:?1?2

public interface OfferRepository extends JpaRepository<Offer, Long> {
    @Query(value = "SELECT *, MIN(6371000 * acos( cos( radians(?1) ) * cos( radians( dest.latitude ) ) * cos( radians( dest.longitude ) - radians(?2) ) + sin( radians(?1) ) * sin( radians( dest.latitude ) ))) as  distance FROM offer dest GROUP BY dest.id having MIN(distance)",
            nativeQuery = true)
    Tuple getClosestOffer(double latitude, double longitude);
}

如果要在日志中显示已解析的参数,只需将 org.hibernate.type 的日志记录级别设置为 trace

application.properties:

spring.jpa.show-sql=true
logging.level.org.hibernate.type=trace