带有动态查询的 Spring Data JPA 分页(可分页) [英] Spring Data JPA Pagination (Pageable) with Dynamic Queries

查看:116
本文介绍了带有动态查询的 Spring Data JPA 分页(可分页)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的查询,如下所示select * from USERS".我还使用 Pageable 来启用分页.

I have a simple query as follows "select * from USERS". I also use Pageable to enable pagination.

此查询可能具有基于给定参数是否为 null 的可选谓词.

This query may have optional predicates based on the given parameters being null or not.

例如,如果给出了code"参数并且不为空,则查询变为"select * from USERS where code = :code";

For example if "code" parameter is given and not null, then the query becomes "select * from USERS where code = :code";

据我所知,我无法使用 @Query 注释来实现这一点.我可以实现自定义存储库并使用 EntityManager 创建动态查询.但是,我不确定如何将Pageable"与它集成以获取分页结果.

As far as I know I cannot implement this using @Query annotation. I can implement a custom repository and use EntityManager to create a dynamic query. However, I am not sure how I can integrate "Pageable" with that to get back paginated results.

我怎样才能做到这一点?

How can I achieve this?

推荐答案

使用 QueryDSL(作为标准 API 的替代方案)在 Spring Data 中很容易做到这一点.它支持开箱即用的以下 QueryDSLPredicateExecutor 方法,如果不应用任何限制,您可以将 null 作为 Predicate 传递:

This is very easy to do in Spring Data using QueryDSL (as alternative to the criteria API). It is supported out of the box with the following method of QueryDSLPredicateExecutor where you can just pass null as the Predicate if no restrictions are to be applied:

Page<T> findAll(com.mysema.query.types.Predicate predicate,
                Pageable pageable)

使用 QueryDSL 可能不适合您,但是如果您查看以下系列教程,您可能会得到一些想法.

Using QueryDSL may not be an option for you however if you look at the following series of tutorials you might get some ideas.

http://www.petrikainulainen.net/编程/spring-framework/spring-data-jpa-tutorial-part-nine-conclusions/

作者在其指南第 9 部分的评论中实际上讨论了您所拥有的场景.

The scenario you have is actually discussed by the author in the comments to part 9 of his guide.

这篇关于带有动态查询的 Spring Data JPA 分页(可分页)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆