Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reverse a findAll() query in the pagingAndSorting repository interface using Spring data REST

I have a Spring JPA rest repository.

public interface SumLogRepository extends PagingAndSortingRepository<SumLog, Long> {

    //custom query method
    List<SumLog> findByFoo(String lastName);

    //How do I make this method return the results in REVERSE order?
    List<SumLog> findAll();

}

I would like the findAll() method to return items in a reverse order.

Since its an interface, I can't override methods directly here.

Is this possible to do?

like image 916
csch0 Avatar asked Sep 15 '25 12:09

csch0


2 Answers

You can use 'OrderBy' and 'Desc' keywords in your query method :

List<SumLog> findAllByOrderByIdDesc();

In this case you get such this SQL query:

select ... from sum_logs sl order by sl.id desc

More info: Query Creation

UPDATED

To change behavior of default methods of repositories you can override them with your own query:

@Query("select sl from SimLog order by sl.id desc")
@Override
List<SumLog> findAll();

@Query("select sl from SimLog order by sl.id desc")
@Override
Page<SumLog> findAll(Pageable pageable);

UPDATED 2

More flexible approach - if sorting order have not set yet, then we set it by 'id desc':

@Override
default Page<SumLog> findAll(Pageable p) {
    if (p.getSort().isUnsorted()) {
        findAllBy(PageRequest.of(p.getPageNumber(), p.getPageSize(), Sort.by(Sort.Direction.DESC, "id")));
    }
    return findAllBy(p);
}

Page<SumLog> findAllBy(Pageable pageable);
like image 54
Cepr0 Avatar answered Sep 18 '25 10:09

Cepr0


I think you can use Pageable for paging & sorting as bellow.

public interface SumLogRepository extends PagingAndSortingRepository<SumLog, Long> {
     Page<SumLog> findAll(Pageable pageable);
}

Example using.

Pageable pageable = new PageRequest(0,20 , new Sort(Sort.Direction.DESC, "id"));
Page<SumLog> pageSumLog = sumLogRepository.findAll(pageable);

And spring can bindding pageable for using in controller like this. (ref: https://docs.spring.io/spring-data/rest/docs/current/reference/html/#paging-and-sorting.sorting)

@GetMapping("/sumlogs")
public ResponseList<SumLog> retrieveLogs(Pageable pageable) {
    Page<SumLog> pageSumLog = sumLogRepository.findAll(pageable)
    return new ResponseList<>(pageSumLog);
}
like image 28
khakhana thimachai Avatar answered Sep 18 '25 08:09

khakhana thimachai