【问题标题】:How to sort By Name and status Active for JPA repository query?如何按名称和状态对 JPA 存储库查询进行排序?
【发布时间】:2019-11-20 22:26:35
【问题描述】:

我正在开发 Spring Boot + Spring Data JPA + Postgres + Lombok 示例。在此示例中,我想获取所有学生 firstName 为 ASC 顺序且其状态为Active

我开发了下面的查询,效果很好,但我没有看到在JpaRepository 查询中也使用status=Active 的方法。

注意:在我的例子中,status 字段在 Java 中是 Enum

如果我们能做到这一点,有什么办法吗?我知道我可以获取所有学生然后使用流可以轻松过滤,但是使用 JpaRepository 查询,有什么办法吗?

List<Student> students = studentRepository.findAll(new Sort(Sort.Direction.ASC, "studentName"));

【问题讨论】:

  • 你可以这样做 findAllByStatusOrderByStudentNameAsc

标签: java postgresql spring-data-jpa jpa-2.2


【解决方案1】:

在扩展 Repository / JpaRepositoryStudentRepository 接口中,您可以添加这样的方法签名:

public interface StudentRepository extends ....{
  List<Student> findAllByStatusOrderByStudentNameAsc(String status);
}

【讨论】:

  • 这不是我发布的相同答案吗。
  • 看来你实际上晚了 1 分钟。
  • @Johna 我和你同时写了我的答案,如果在你之后几秒钟就提交了。我会给你的答案投票。
  • @riorio 我明白了,朋友。这里没有竞争,如果他找到了问题的答案,就是这样。
【解决方案2】:

只需将以下方法签名放入您的存储库中,并使用参数“Active”在您需要的地方调用它。

List<Student> findAllByStatusOrderByStudentNameAsc(String status);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-10
    • 2023-01-14
    • 2021-11-03
    • 1970-01-01
    • 2021-09-05
    相关资源
    最近更新 更多