【问题标题】:How to get top results using specifications in spring data jpa?如何使用 spring data jpa 中的规范获得最佳结果?
【发布时间】:2018-06-15 04:31:01
【问题描述】:

我对 Spring Data jpa 很陌生。我正在尝试在查询数据库时使用规范。我的问题是使用 crudrepository 我们可以像这样:

findTopByUsernameOrderByUpdatedAtDesc(String username);

如何使用规范实现相同的目标?我可以做一些基本的事情,比如和或规范,但不像我们可以用标准等做的那样健壮。

Specification<CustomClass> spec = Specifications.where(specification).and(username);
List<CustomClass> list = findAll(spec);

【问题讨论】:

  • 删除了关于要求教程和东西的部分,因为它提出了一个很好的问题。
  • 其实我会order结果列表,你的结果会排在首位。
  • 你用一半的信息询问,规范可以用谓词和查询构建器构建

标签: spring spring-boot spring-data-jpa jpa-criteria


【解决方案1】:

这样做如下:

 Pageable pageable = new PageRequest(0, 1, Sort.Direction.DESC, "username");
 Page oneElementPage = repository.findAll(spec, pageable);

这将对用户名列中的数据进行降序排序并返回第一个结果。

【讨论】:

    【解决方案2】:

    您不能直接在Specification 中表达这一点。但是您可以为此使用Pageable

    Page oneElementPage = repository.findAll(spec, new PageRequest(0, 1));
    

    给你一个带有单个元素的Page

    【讨论】:

    • 这样可以吗:Pageable pageable = PageRequest(0, 1, Sort.Direction.DESC, "username");然后将其传递给 findAll(spec,pageable); ?
    • 这样想。试试看吧。
    猜你喜欢
    • 2016-01-06
    • 2019-05-25
    • 1970-01-01
    • 2022-11-21
    • 2016-07-22
    • 2013-03-22
    • 1970-01-01
    • 2017-06-01
    • 2021-07-17
    相关资源
    最近更新 更多