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?
4 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()
-
Yes this would be an option. However I would like the standard findAll() method to use a specific order. The reason is I'm using @Cacheable on it as well. Mar 13, 2015 at 11:31
-
-
Yes I understand I can use this. But I wonder if it's possible to in general set default sorting for entity. I guess not. Mar 13, 2015 at 13:09
-
-
2
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:
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
If you want to add costom query to findAll() jpa query you can do it this way
here i changed my default order
According to my default order is primary key it is id
but now i here set id_order to change my default order
Model class
@Entity
@Table(name = "category")
@NamedQuery(name = "Category.findAll", query="select u from Category u order by
u.id_order")
public class Category {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String nameEn;
private String nameSi;
private String nameTa;
private Integer id_order;
Repository class
import com.model.Category;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import java.util.List;
public interface CategoryRepository extends CrudRepository<Category, Integer> {
@Override
@Query
public Iterable<Category> findAll();
SimpleJpaRepository
and override thefindAll
method. See the section on Adding custom behavior to all repositories. You can also use this to override to default behavior.