【问题标题】:Filtering data with Spring boot CrudRepository使用 Spring Boot CrudRepository 过滤数据
【发布时间】:2016-02-12 07:37:29
【问题描述】:

我有一个简单的 REST 服务,它使用 Spring boot 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 &gt; 13 AND id &lt; 27 的实体)。 CrudRepository 似乎不支持此功能。有什么方法可以实现这一点还是我需要使用不同的方法?

感谢您的任何提示!

【问题讨论】:

    标签: java rest spring-boot spring-data spring-data-jpa


    【解决方案1】:

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

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

    然后您可以从存储库实例调用此函数。更多信息请参考spring-data reference..

    【讨论】:

    • 这个可以和Pageable结合吗?我希望我可以在某个对象中指定它并将其传递给函数。当需要一些灵活性时,这不是很方便(用户可以指定要过滤的自定义字段,我必须为每个可能的组合指定这样的函数......)
    • 是的,你可以简单地使用List&lt;Flight&gt; findByIdBetween(Long start, Long end, Pageable pageable)
    • 也推荐你把扩展接口改成PagingAndSortingRepository..
    • 考虑到这项工作,我应该在我的http请求中发送什么来使用这种方法?
    【解决方案2】:

    另一种方法可以解决您在上述 cmets 中关于必须为每个参数组合创建查询方法的担忧,即通过 Criteria API 或使用 QueryDSL 使用规范模式。

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

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

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-04
      • 2016-07-01
      • 2018-08-01
      • 2019-07-16
      • 2017-10-01
      • 1970-01-01
      • 2017-11-17
      • 1970-01-01
      相关资源
      最近更新 更多