本文介绍了使用 Spring Boot CrudRepository 过滤数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a simple REST service which access data with Spring boot CrudRepository.

这个存储库已经实现了这样的分页和排序功能:

This repository already implements pagination and sorting capabilities like this:

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 的实体).CrudRepository 似乎不支持此功能.有什么方法可以实现这一点还是我需要使用不同的方法?

I would like to add also filtering to this repository (for example return only entities with id > 13 AND id < 27). The CrudRepository does not seem to support this functionality. Is there some way how to achieve this or do I need to use different approach?

感谢您的建议!

推荐答案

另一种替代方案是通过以下任一方式使用规范模式Criteria API 或使用 QueryDSL.

An alternative, which would address your concern in the comments above about having to create query methods for every combination of parameters, is to use the Specification pattern via either the Criteria API or by using QueryDSL.

下面概述了两种方法,以应对以下问题:

Both approaches are outlined at the below in response to the concern that:

对于较大的应用程序,查询方法的数量可能会增加,因为of - 这是第二点 - 查询定义了一组固定的标准.为了避免这两个缺点,如果你可以想出一组可以组合的原子谓词动态构建您的查询?

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

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

I find QueryDSL a bit easier to work with. You need only define one interface method which you can then pass any combination of parameters to as a predicate.

例如

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 自动生成的类.

where QUser is a QueryDSL auto-generated class.

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

http://www.querydsl.com/静态/querydsl/2.1.0/reference/html/ch02s02.html

更新

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

From the Gosling release of the Spring Data module there is now support for automatic predicate generation from HTTP parameters in a web application.

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

这篇关于使用 Spring Boot CrudRepository 过滤数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 19:45