java - 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?
解决方案
Spring data JPA中有两种对结果进行排序的方法
使用自定义 JPA 查询如下
@Query("Select r from rack order by position_number ASC")
使用 JPA 自定义方法(如您所用:(
findByRackOrderByPositionNumberAsc
))在存储库方法中传递排序对象如下
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);
推荐阅读
- java - @Transactional:事务结束时不提交;使用 Spring Boot 和 neo4j
- python - 比较来自不同文件的单词
- c# - 如何在停止/播放动画中的某个位置启动进度条?[Xamarin 形式]
- javascript - React-Table:类型无效,预期字符串(正确导入/导出)
- javascript - 删除当前用户后如何链接WithCredential?
- java - 如何扩展 SL4J 使其将日志放入 Kinesis 流
- python - 在 centos 6.10 python 3.6 上运行 Scrapyd 作为守护进程
- javascript - 如何使用 laravel 和客户端执行 web scapring
- javascript - 如果会话在javascript中登录(laravel 5.6)
- python - 我想在“|”之前对字符串的第一部分进行切片