简体   繁体   English

自定义方法排序Spring数据JPA

[英]Custom Method Sorting Spring Data JPA

is there possibility to use Java method to sort JPA result? 是否有可能使用Java方法对JPA结果进行排序?

I have entity: 我有实体:

+--------+----------+-----------+
| Name   | Latitude | Longitude |
+--------+----------+-----------+
| A      | x1       | y1        |
| B      | x2       | y2        |
| C      | x3       | y3        |
+--------+----------+-----------+

I mean instead of writing SQL: 我的意思是不是写SQL:

    "  ORDER BY (acos(sin(latitude * $RADIAN) * sin(:latitude * $RADIAN)" +
    "       + cos(latitude * $RADIAN) * cos(:latitude * $RADIAN)" +
    "         * cos((:longitude * $RADIAN) - (longitude * $RADIAN))" +
    "  ) * $EARTH_RADIUS)")
fun findDoctorDepartmentsInRange(@Param("latitude") latitude: Double,
                                 @Param("longitude") longitude: Double)

I've tried with Specification but how to inject custom java method into EXPRESSION used below: 我已尝试使用Specification,但如何将自定义java方法注入到下面使用的EXPRESSION中:

query.orderBy(cb.asc(EXPRESSION))

If you are using Spring JPA, you could use Sort object, and you append it not in your specification but to your query 如果您使用的是Spring JPA,则可以使用Sort对象,然后将其不添加到规范中,而是添加到查询中

as far as i remember sntax will be something like that 据我记得sntax将是这样的

repository.findAll(specification,  new Sort(Sort.Direction.ASC, "field"));

Edit 编辑

I'm not sure is Sort supports expressions, so if you want to do this in java code, you need to create Criteria API query, which will be something like that 我不确定Sort支持表达式,因此,如果要在Java代码中执行此操作,则需要创建Criteria API查询,该查询类似于

CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<SomeClass> query = cb.createQuery(SomeClass.class);
Root<SomeClass> root = query.from(SomeClass.class);
Expression EXPRESSION = <<TypeYourExpression>>;
query.orderBy(cb.asc(EXPRESSION))
query.where(specification.toPredicate(root,query,cb))
List<SomeClass> result = em.createQuery(query).getResultList();

You can't have java code as your ORDER BY expression in general. 通常,您不能将Java代码用作ORDER BY表达式。 Not in SQL nor in JPA. 不在SQL或JPA中。

Some databases (at least Oracle) allow you to define Stored Procedures in Java, so in theory, you probably can write an SP in Java and use the that in an ORDER BY expression. 有些数据库(至少是Oracle)允许您用Java定义存储过程,因此从理论上讲,您可能可以用Java编写SP,并在ORDER BY表达式中使用SP。

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

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