如何在Spring Data Jpa中找到前N个元素?

Vit*_*lii 5 spring-data spring-data-jpa

在 Spring Data Jpa 中获取前 10 行我可以做到这一点findTop10By...()。在我的情况下,数字或行没有定义,而是作为参数出现的。

有类似的东西findTopNBy...(int countOfRowsToGet)吗?

Vit*_*lii 20

这是另一种没有本地查询的方法。我Pageable作为参数添加到接口中的方法中。

findAllBySomeField(..., Pageable pageable)
Run Code Online (Sandbox Code Playgroud)

我这样称呼它:

findAllBySomeField(..., PageRequest.of(0, limit)) //  get first N rows
findAllBySomeField(..., Pageable.unpaged()) //  get all rows
Run Code Online (Sandbox Code Playgroud)


小智 8

正如第一个答案中所述,通过使用分页来完成。只是添加一个更明确的示例。

此示例将为您提供按 id 排序的前 50 条记录。

存储库:

@Repository
public interface MyRepository extends JpaRepository<MyEntity, String> {
    Page<MyEntity> findAll(Pageable pageable);  
}
Run Code Online (Sandbox Code Playgroud)

服务:

@Service
public class MyDataService {

    @Autowired
    MyRepository myRepository;

    private static final int LIMIT = 50;
    
    public Optional<List<MyEntity>> getAllLimited() {
        Page<MyEntity> page = myRepository.findAll(PageRequest.of(0, LIMIT, Sort.by(Sort.Order.asc("id"))));
        return Optional.of(page.getContent());
    }
}
Run Code Online (Sandbox Code Playgroud)

在这里找到了最初的想法: https: //itqna.net/questions/16074/spring-data-jpa-does-not-recognize-sql-limit-command (这也将链接到另一个SO问题顺便说一句)