Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 316
Prashant Shilimkar Avatar asked Aug 25 '14 13:08

Prashant Shilimkar


People also ask

How do you write orderBy in JPA?

With JPA Criteria – the orderBy method is a “one stop” alternative to set all sorting parameters: both the order direction and the attributes to sort by can be set. Following is the method's API: orderBy(CriteriaBuilder. asc): Sorts in ascending order.

How do you get data in descending order in spring boot?

4.1. One option is to use Spring Data's method derivation, whereby the query is generated from the method name and signature. All we need to do here to sort our data is include the keyword OrderBy in our method name, along with the property name(s) and direction (Asc or Desc) by which we want to sort.

What is findAll in Spring JPA?

Spring Data JPA - findAll() Method Example As the name depicts, the findAll() method allows us to get or retrieve all the entities from the database table. In this example, we will use the Product entity to save and retrieve to/from the MySQL database.


1 Answers

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"        ^ 
like image 179
Sikor Avatar answered Oct 11 '22 20:10

Sikor