代码之家  ›  专栏  ›  技术社区  ›  Snæbjørn

JpaRepository排序方法中的自定义SQL排序

  •  1
  • Snæbjørn  · 技术社区  · 6 年前

    是否可以使用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 所以在我下兔子洞之前想知道我在做什么是可能的。

    1 回复  |  直到 6 年前
        1
  •  0
  •   Assafs    6 年前

    如果有可比较的属性名,则可以使用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”作为sort by属性,方法是:

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