Search code examples
javapostgresqlspring-data-jpajpa-2.2

How to sort By Name and status Active for JPA repository query?


I am developing Spring Boot + Spring Data JPA + Postgres + Lombok example. In this example, I want to fetch all student firstName is ASC order and whose status in Active.

I developed below query, which works fine, but I don't see a way to also use status=Active here in JpaRepository query.

Note: In my case, status field is Enum in Java.

Is there any way if we can do the same? I know I can fetch all students and then using streams can easily filter, but using JpaRepository query, is there any way?

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

Solution

  • In your StudentRepository interface, that extends Repository / JpaRepository you can add a method signature like that:

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