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?
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.
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.
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.
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" ^
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With