Search code examples
springspring-dataspring-data-jpa

How to use OrderBy with findAll in Spring Data


I am using spring data and my DAO looks like

public interface StudentDAO extends JpaRepository<StudentEntity, Integer> {
    public findAllOrderByIdAsc();   // I want to use some thing like this
}

In above code, commented line shows my intent. Can spring Data provides inbuilt functionality to use such a method to find all records order by some column with ASC/DESC?


Solution

  • public interface StudentDAO extends JpaRepository<StudentEntity, Integer> {
        public List<StudentEntity> findAllByOrderByIdAsc();
    }
    

    The code above should work. I'm using something similar:

    public List<Pilot> findTop10ByOrderByLevelDesc();
    

    It returns 10 rows with the highest level.

    IMPORTANT: Since I've been told that it's easy to miss the key point of this answer, here's a little clarification:

    findAllByOrderByIdAsc(); // don't miss "by"
           ^