为了账号安全,请及时绑定邮箱和手机立即绑定

如何通过分页搜索任何字段

如何通过分页搜索任何字段

POPMUISE 2022-06-30 19:14:29
我有一个用例,我需要找到分页的客户列表,其中客户看起来像这样:@Entitypublic class Customer {    @Id    private Long id;    private String firstName;    private String lastName;    private String phone;    private String mail;}然后我有我的存储库界面public interface CustomerRepository extends PagingAndSortingRepository<Customer, Long> {Optional<Customer> findById(Long id);...}我的界面扩展了 PagingAndSortingRepository 以提供可分页的结果。我还有一个输入框,用户可以在其中输入任何字符串。现在我想向他返回一页结果,其中包含一个字段(任何客户字段)中的输入字符串。我不想使用命名查询。有没有一种聪明的方法可以通过 PagingAndSortingRepository 存储库实现这一点,还是我需要使用规范接口并实现分页?
查看完整描述

1 回答

?
慕虎7371278

TA贡献1802条经验 获得超4个赞

你不能这样做:


@Query("select c from Customer c where c.firstName like :filter" 

           + " or c.lastName like :filter or c.emailAddress like :filter.......")

Page<Customer> filter(@Param("filter") String filter);

或者,您可以使用 QueryDsl。


扩展附加接口:


public interface CustomerRepository extends PagingAndSortingRepository<Customer, Long>, QueryDslPredicateExecutor<Customer>{


}

添加相关的构建工具:


然后您可以调用继承的方法:


Page<Customer> findAll(Predicate predicate, Pageable pageable)

像这样使用:


Page<Customer> page =repo.findAll(QCustomer.customer.firstName.like(filter)

     .or(QCustomer.customer.lastName.like(filter).or(...));

参考:


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


查看完整回答
反对 回复 2022-06-30
  • 1 回答
  • 0 关注
  • 171 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号