java - JpaRepository中通过自定义SQL排序方法排序

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

是否可以使用 JPA 查询方法表达以下查询?

  @Query(
      value =
          "SELECT a FROM #{#entityName} a"
              + "LEFT JOIN Other o ON a.otherId = o.id"
              + "ORDER BY CASE WHEN o.foo = 'A' then 1"
              + "              WHEN o.foo = 'S' then 2"
              + "              WHEN o.foo = 'D' then 3"
              + "              ELSE 4"
              + "         END, a.createdDate DESC NULLS LAST")
  List<T> findAllCustomSorted();

像这样的查询方法

List<T> findAll(Sort sort);

调用了类似的东西

String fooProperty = "CASE WHEN o.foo = 'A' then 1"
                        + "WHEN o.foo = 'S' then 2"
                        + "WHEN o.foo = 'D' then 3"
                        + "ELSE 4"
                    + END;
String dateProperty = "createdDate";
repo.findAll(
    new Sort(
        new Order(Direction.ASC, fooProperty, NullHandling.NULLS_LAST),
        new Order(Direction.DESC, dateProperty, NullHandling.NULLS_LAST)));

现在这不起作用。

但是我发现了一些名为 JpaSort.unsafe()JpaPath 的东西,所以想知道在我陷入兔子洞之前我想做的事情是否可能。

最佳答案

如果您有可比较的属性名称,则可以使用排序。尝试更改您使用的选择查询以将排序键包含为另一列:

@Query(
  value =
      "SELECT a, CASE WHEN o.foo = 'A' then 1"
          + "              WHEN o.foo = 'S' then 2"
          + "              WHEN o.foo = 'D' then 3"
          + "              ELSE 4"
          + "         END sort FROM #{#entityName} a"
          + "LEFT JOIN Other o ON a.otherId = o.id"
          + "ORDER BY a.createdDate DESC NULLS LAST")
List<T> findAllCustomSorted();

这意味着您的结果将有两列 - a 及其排序键。现在您可以使用“sort”作为按属性排序:

repo.findAll(new Sort(Sort.Direction.ASC, "sort"));

关于java - JpaRepository中通过自定义SQL排序方法排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54091661/

相关文章:

Java Get access token using Client Credentials 授予和存储 token

java - 在双数组中尝试并捕获未按我的预期工作

java - HQL hibernate 左连接 where 子句

java - 添加一些jar后无法启动Tomcat-8.5.20

java - 在新版本的 Hibernate View 中打开 session

java - 如何获取可嵌入的更改?

java - 从 Sonar 覆盖报告中排除 Lombok 类

java - Java 中 outData.writeInt() 的作用是什么?

java - 循环无法启动

java - 无法验证用户是否是 Google Apps 中的管理员