spring-data-rest

Spring Data Rest specify default order by


I am new to Spring Data Rest and looks like exactly I want to use to easily expose some existing database tables as restful services. I have managed to get an example working by following this guide. This works but how would I display all rows ordered by a creation date field by default?

I tried adding a findAllByOrderByCreationdateDesc() method which appears as a new search method through the REST interface but I would ideally like to do this by default when all items are displayed.

Any pointers would be great.


Solution

  • You can try to override the findAll() method in you repository interface:

    @RepositoryRestResource
    public interface UserRepo extends JpaRepository<User, Long> {
    
        @Override 
        @Query("select u from User u order by u.name asc")
        Page<User> findAll(Pageable pageable);
    }
    

    But in this case you will lose the ability to use arbitrary sorting (for example: /users?sort=name,desc). And you will have unnecessary search resource link /users/search/findAll{?page,size,sort}