首页 > 解决方案 > 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?

标签: javaspringspring-bootspring-data-rest

解决方案


Spring data JPA中有两种对结果进行排序的方法

  1. 使用自定义 JPA 查询如下

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

  2. 使用 JPA 自定义方法(如您所用:( findByRackOrderByPositionNumberAsc))

  3. 在存储库方法中传递排序对象如下

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

并调用如下方法

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

推荐阅读