Spring Data:限制自定义查询的结果

7
在我的Spring Data存储库中,我必须使用@Query注释来使用自定义查询。我知道我可以像这样在命名查询中限制结果的数量: Iterable<Person> findFirst5OrderByLastName() 或者通过传递一个可分页的方式来限制结果的数量,如下所示: Iterable<Person> findByLastName(String lastName, Pageable pageable) 但是,在使用自定义@Query注释时是否可能实现相同的效果?
谢谢!

可能是 setMaxResults for Spring-Data-JPA annotation? 的重复问题。 - dev4Fun
我在那里添加了一些澄清,解释为什么我认为这不是重复/没有得到答案。 - portux
5个回答

3
你可以尝试这个方法:
@Entity
@Table(name = "persons") 
public class Person {
    //...
}

@Query(value = "select * from persons limit 50", nativeQuery = true)
List<Person> getFirst50();

不要忘记检查你的SQL服务器是否支持limit关键字。


1
我建议添加 "By" 但不带参数,这将起作用:
List<Person> findTop100By();

1

1
问题与如何限制查询结果大小有关,而不是排序。 - Anand

0

你好,你可以尝试这个

@Query("...")
List<YourDTO>getData(Pageable pageable)

在你的serviceImpl中

    List<YourDTO> getData(){
    int limit=10;
    Pageable pageable = PageRequest.of(0, limit);
    return this.repo.getData(pageable);
}

你应该避免使用 nativeQuery


0

你需要扩展PagingAndSortingRepository

并添加方法

Page<Person> listAllByPage(Pageable pageable)

请查看示例


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接