繁体   English   中英

使用Spring引导CrudRepository过滤数据

[英]Filtering data with Spring boot CrudRepository

我有一个简单的REST服务,它使用Spring启动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似乎不支持此功能。 有没有办法如何实现这一点,还是我需要使用不同的方法?

谢谢你的任何提示!

另一种方法是在上面的注释中解决您关于必须为每个参数组合创建查询方法的问题,即通过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数据模块的Gosling版本开始,现在支持从Web应用程序中的HTTP参数生成自动谓词。

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

在您的存储库中声明以下函数[EDITED]

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

然后,您可以从存储库的实例调用此函数。 有关详细信息,请参阅弹簧数据参考

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM