在 mariadb 中,我创建了计算用户点和地点点之间距离的函数
/* create function */
DELIMITER $$
CREATE
FUNCTION `u_st_distance_sphere`(`user_point` POINT, `place_point` POINT)
RETURNS double
BEGIN
return (6371*acos(cos(radians(ST_X(user_point)))*cos(radians(ST_X(place_point)))*cos(radians(ST_Y(place_point))
-radians(ST_Y(user_point)))+sin(radians(ST_X(user_point)))*sin(radians(ST_X(place_point)))));
END$$
DELIMITER ;
要使用该函数,请在 CustomDialect 类中注册函数并在 .yml 中应用
public class MariadbCustomDialect extends MariaDB103Dialect {
public MariadbCustomDialect() {
super();
this.registerFunction(
"u_st_distance_sphere",
new StandardSQLFunction("u_st_distance_sphere", StandardBasicTypes.DOUBLE)
);
}
}
spring:
...
jpa:
...
database-platform: ...global.config.MariadbCustomDialect
我想制作用点计算的距离列并按距离升序排序
//in PlaceCustomRepository
//making filtered JPQLQuery
String pointWKT = String.format("POINT(%s %s)",
placeFilterParam.getLatitude(),
placeFilterParam.getLongitude());
NumberTemplate<Double> expr = Expressions.numberTemplate(
Double.class,
"u_st_distance_sphere( ST_GeomFromText({0}), ST_GeomFromText({1}) )",
pointWKT,
place.point);
JPQLQuery<PlaceResponseTest> query = jpaQueryFactory
.select(
new QPlaceResponseTest(place.id,
expr.as("distance")))
.from(place)
.orderBy();
如何指定距离列?
谢谢
我发现使用常量表达式可以工作
JPQLQuery<PlaceResponseTest> query = jpaQueryFactory
.select(
new QPlaceResponseTest(place.id,
expr.as("distance")))
.from(place)
.orderBy(new OrderSpecifier<>(Order.ASC, Expressions.constant("distance")));