使用Spring Boot CrudRepository过滤数据

18

我有一个使用Spring Boot的简单REST服务,它使用CrudRepository访问数据。

这个仓库已经实现了分页和排序功能,就像这样:

public interface FlightRepository extends CrudRepository<Flight, Long> {
  List<Flight> findAll(Pageable pageable);
}

叫它:

Sort sort = new Sort(direction, ordering);
PageRequest page = new PageRequest(xoffset, xbase, sort);

return flightRepo.findAll(page);
我希望在这个存储库中添加筛选功能(例如仅返回带有id > 13 AND id < 27的实体)。 CrudRepository似乎不支持此功能。是否有某种方法可以实现这一点,还是我需要使用不同的方法?
谢谢任何提示!
2个回答

15

一种替代方法是使用规约模式,可以通过Criteria API或使用QueryDSL来解决您在上面评论中提到的需要为每个参数组合创建查询方法的问题。

针对以下问题,这两种方法都在下面进行了概述:

由于查询定义了一组固定的条件,因此在更大的应用程序中,查询方法的数量可能会增加 - 这是第二个要点。为避免这两个缺点,是否可以想出一组原子谓词,动态地将其组合以构建查询?

https://spring.io/blog/2011/04/26/advanced-spring-data-jpa-specifications-and-querydsl/

我发现使用QueryDSL比较容易。您只需定义一个接口方法,然后可以将任何参数组合作为谓词传递给它。

例如:

public interface UserRepository extends PagingAndSortingRepository<User, Long>, QueryDslPredicateExecutor<User> {
    public List<User> findAll(Predicate predicate);
}

并查询:

repository.findAll(QUser.user.address.town.eq("Glasgow").and(QUser.user.gender.eq(Gender.M)));

repository.findAll(QUser.user.address.town.eq("Edinburgh"));

repository.findAll(QUser.user.foreName.eq("Jim"));

QUser是由QueryDSL自动生成的类。

http://docs.spring.io/spring-data/jpa/docs/current/api/index.html?org/springframework/data/jpa/repository/support/QueryDslRepositorySupport.html

http://www.querydsl.com/static/querydsl/2.1.0/reference/html/ch02s02.html

更新

从Spring Data的Gosling版本开始,支持在Web应用程序中从HTTP参数自动生成谓词。

https://spring.io/blog/2015/09/04/what-s-new-in-spring-data-release-gosling#querydsl-web-support


2

在您的代码库中声明以下函数:[已编辑]

Page<Flight> findByIdBetween(Long start, Long end, Pageable pageable)

然后,您可以从存储库实例中调用此函数。有关更多信息,请参阅spring-data参考文档。请参考spring-data reference

这个能和Pageable结合吗?我希望能够在某个对象中指定它并将其传递给函数。当想要一些灵活性时,这并不是很方便(用户可能会指定要过滤的自定义字段,而我必须为每种可能的组合指定一个这样的函数...) - Smajl
是的,你可以简单地使用 List<Flight> findByIdBetween(Long start, Long end, Pageable pageable) - pezetem
还建议您将扩展接口更改为PagingAndSortingRepository - Jos
考虑到这项工作,我应该在我的HTTP请求中发送什么以使用这种方法? - Dimitri Kopriwa

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接