[英]calculating distance between two coordinates SQL + Criteria Builder
所以在我的代码中,我希望能够使用一些参考坐标检查哪些坐标在范围内。 一开始我使用的是一些本机 SQL 查询,例如:
@Query(
value = "SELECT * FROM event " +
" inner join event_location location on location.id = event.location_id\n" +
" where Round( ST_Distance_Sphere(\n" +
" Point(?1 , ?2 )," +
" Point(location.longtitude , location.latitude ), 4326), 2) <= ?3",
nativeQuery = true)
List<Event> findAllEventsInRange(double longtitude, double latitude, String range);
它工作得很好,但现在我想将规范与标准构建器一起使用。 老实说,我不知道如何在 where 关键字之后写条件。
谁能让我知道我该怎么做?
编辑:实体已定义。 而且我已经创建了现在加入两个表的规范 - 事件和事件位置:
public static Specification<Event> filter(Search search){
return (root, cq, cb) -> {
Predicate location = null;
List<Predicate> result = new ArrayList<>();
if(search.getLat() != null && search.getLng() != null && search.getRange() != null) {
Join<Event,EventLocation> join = root.join("eventLocation", JoinType.LEFT);
}
return cb.and(result.toArray(new Predicate[result.size()]));
};
}
现在我需要创建一个正确的谓词,它将与 WHERE 之后的语句执行相同的操作。 I know there is function on criteria builder which can be used for some native sql function but not sure how i can use it in my case and combine with different other sql functions as well.
为此,您需要使用通用的 function 调用语法,如下所示:
public static Specification<Event> filter(Search search){
return (root, cq, cb) -> {
Predicate location = null;
List<Predicate> result = new ArrayList<>();
if(search.getLat() != null && search.getLng() != null && search.getRange() != null) {
Join<Event,EventLocation> join = root.join("eventLocation", JoinType.LEFT);
result.add(
cb.le(
cb.function("Round", String.class,
cb.function("ST_Distance_Sphere", String.class,
cb.function("Point", String.class,
cb.literal(search.getLat()),
cb.literal(search.getLng())
),
cb.function("Point", String.class,
join.get("longtitude"),
join.get("latitude ")
),
cb.literal(4326)
),
cb.literal(2)
),
cb.literal(search.getRange())
)
);
}
return cb.and(result.toArray(new Predicate[result.size()]));
};
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.