Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change default sort order for Spring Data findAll() method

I'm using Spring Data JPA and I wonder if it is possible to change the default sort order for a entity being used by the Spring Data findAll() method?

like image 452
Marcel Overdijk Avatar asked Mar 13 '15 11:03

Marcel Overdijk


Video Answer


3 Answers

You can achieve this as follows:

dao.findAll(new Sort(Sort.Direction.DESC, "colName"));
// or
dao.findAll(Sort.by("colName").descending());

Another way to achieve the same. Use the below method name:

findByOrderByIdAsc()
like image 140
Mithun Avatar answered Oct 19 '22 16:10

Mithun


You should be able to do this by either:

in spring-data 1.5+, overriding the findAll() method in your Interface, adding the @Query annotation and creating a named Query in your Entity class like, for example, below:

Entity

@Entity
@NamedQuery(name = "User.findAll", query="select u from User u order by u.address.town")
public class User{

}

Repository

public interface UserRepository extends ... <User, Long> {

    @Override
    @Query
    public Iterable<User> findAll();
}

or,

by creating a custom repository implementation:

http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.custom-implementations

like image 7
Alan Hay Avatar answered Oct 19 '22 15:10

Alan Hay


Use a PagingAndSortingRepository instead. With that in place you can add a queryparameter ?sort=,

Repository:

public interface UserRepository extends PagingAndSortingRepository<User, Long> {
  //no custom code needed
}

GET Request:

localhost:8080/users?sort=name,desc
like image 2
Matthias Avatar answered Oct 19 '22 16:10

Matthias