首頁  >  文章  >  Java  >  如何限制 Spring-Data-JPA 查詢方法中的結果?

如何限制 Spring-Data-JPA 查詢方法中的結果?

Mary-Kate Olsen
Mary-Kate Olsen原創
2024-10-28 02:42:02932瀏覽

How to Limit Results in Spring-Data-JPA Query Methods?

如何在Spring-Data-JPA 中使用setMaxResults 註解

您的問題涉及設定查詢方法在Spring- Data-JPA 中使用註解。

解決方案

由於Spring Data JPA 1.7.0(Evans 版本系列)引入了Top 和First 關鍵字,您可以定義像這樣的查詢方法:

findTop10ByLastnameOrderByFirstnameAsc(String lastname);

Spring Data 會自動將結果限制為指定數量(如果省略,則預設為1)。請記住,在這種情況下,結果的排序變得非常重要。

先前的版本

在早期版本中,Spring Data 使用分頁抽象來擷取資料切片。使用方法如下:

public interface UserRepository extends Repository<User, Long> {

  List<User> findByUsername(String username, Pageable pageable);
}

//...

Pageable topTen = new PageRequest(0, 10);
List<User> result = repository.findByUsername("Matthews", topTen);

如果需要結果的上下文,可以使用Page作為返回類型:

public interface UserRepository extends Repository<User, Long> {

  Page<User> findByUsername(String username, Pageable pageable);
}

//...

Pageable topTen = new PageRequest(0, 10);
Page<User> result = repository.findByUsername("Matthews", topTen);
Assert.assertThat(result.isFirstPage(), is(true));

注意使用Page作為返回類型將觸發計數投影以確定元素的總數。

以上是如何限制 Spring-Data-JPA 查詢方法中的結果?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn