Matthew Satti
Matthew Satti

Reputation: 103

Spring Data REST "findBy..." not sorting

I have a Spring Boot API (using 2.0.5.RELEASE spring-boot-starter-parent) and I'm using the spring-boot-starter-rest package to generate the endpoints for my API. In one of the repositories I have the following method:

@Repository
public interface RackPositionDao extends JpaRepository<RackPosition, String> {
    List<RackPosition> findByRack(@Param("rack") Rack rack);
}

Which exposes an endpoint at http://{base}/api/v1/rackPositions/findByRack

If I then call

http://{base}/api/v1/rackPositions/findByRack?rack={rack url}&sort=positionNumber,asc

in Postman, the list returned isn't sorted. 'positionNumber' is a property on the RackPosition entity.

However if I change the repository method to

@Repository
public interface RackPositionDao extends JpaRepository<RackPosition, String> {
    List<RackPosition> findByRackOrderByPositionNumberAsc(@Param("rack") Rack rack);
}

and then call

http://{base}/api/v1/rackPositions/findByRackOrderByPositionNumberAsc?rack={rack url}

it works fine. Is there a reason why the sort parameter doesn't work?

Upvotes: 0

Views: 1755

Answers (3)

TheSprinter
TheSprinter

Reputation: 1528

There are 2 ways to sort result in Spring data JPA

  1. Using Custom JPA Query as below

    @Query("Select r from rack order by position_number ASC")

  2. Using JPA custom methods (as you used : findByRackOrderByPositionNumberAsc())

  3. Passing Sort object in repository method as below

    List<RackPosition> findByRack(@Param("rack") Rack rack,org.springframework.data.domain.Sort sort);

and call the method as below

Sort sort = new Sort(new Sort.Order(Direction.ASC, "lastName"));
Object obj  = repo.findByRack(rackObject, sort);

Upvotes: 2

WGSSAMINTHA
WGSSAMINTHA

Reputation: 190

JpaRepository interface extends PagingAndSortingRepository interface.

So, you can use endpoint as
http://{base}/api/v1/rackPositions/findbyRack or http://{base}/api/v1/rackPositions/find-byRack
by avoiding camel caps.

Upvotes: 0

darshakat
darshakat

Reputation: 689

Please follow this : https://docs.spring.io/spring-data/jpa/docs/current/api/org/springframework/data/jpa/repository/JpaRepository.html

<S extends T> List<S> findAll(Example<S> example, Sort sort)

Upvotes: 0

Related Questions