5.3.5. 使用Sort

5.3.5. 使用Sort

5.3.5. Using Sort

提供PageRequest或者直接使用Sort可以启用排序。在Sort的实例Order中使用的属性需要匹配你的域模型,意味着需要匹配一个属性或者在查询中使用别名。JPQL将此定义为一个状态字段路径表达式。

Sorting can be done be either providing a PageRequest or by using Sort directly. The properties actually used within the Order instances of Sort need to match your domain model, which means they need to resolve to either a property or an alias used within the query. The JPQL defines this as a state field path expression.

但同时使用@QuerySort会使Order实例的ORDER BY语句中包含函数。原因是Order添加了指定的查询字符串。默认Spring Data JPA拒绝所有包含函数调用的Order实例,但你可以使用JpaSort.unsafe来添加潜在的非安全排序。

However, using Sort together with @Query lets you sneak in non-path-checked Order instances containing functions within the ORDER BY clause. This is possible because the Order is appended to the given query string. By default, Spring Data JPA rejects any Order instance containing function calls, but you can use JpaSort.unsafe to add potentially unsafe ordering.

下面的例子使用了SortJpaSort,包括JpaSort的一种不安全选项。

The following example uses Sort and JpaSort, including an unsafe option on JpaSort:

例60. 使用SortJpaSort

Example 60. Using Sort and JpaSort

public interface UserRepository extends JpaRepository<User, Long> {

  @Query("select u from User u where u.lastname like ?1%")
  List<User> findByAndSort(String lastname, Sort sort);

  @Query("select u.id, LENGTH(u.firstname) as fn_len from User u where u.lastname like ?1%")
  List<Object[]> findByAsArrayAndSort(String lastname, Sort sort);
}

repo.findByAndSort("lannister", new Sort("firstname"));               // 1
repo.findByAndSort("stark", new Sort("LENGTH(firstname)"));           // 2
repo.findByAndSort("targaryen", JpaSort.unsafe("LENGTH(firstname)")); // 3
repo.findByAsArrayAndSort("bolton", new Sort("fn_len"));              // 4
  1. 指向了领域模型的属性的合法Sort表达式。
  2. 包含了函数调用的不合法Sort。会抛异常。
  3. 包含了指定unsafe Order的合法Sort
  4. 指定别名函数的合法Sort表达式。
  1. Valid Sort expression pointing to property in domain model.
  2. Invalid Sort containing function call. Throws Exception.
  3. Valid Sort containing explicitly unsafe Order.
  4. Valid Sort expression pointing to aliased function.

翻译部分版权归YahaCode团队所有。仅供学习研究之用,任何组织或个人不得私自以此用于任何形式的商业目的

发表评论