在 JpaRepository Sort 方法中按自定义 SQL 排序



是否可以使用 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想知道在我进入兔子洞之前,我是否应该做的事情是可能的。

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

@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"));

最新更新