具有动态查询的Spring Data JPA分页(可分页)

led*_*led 16 pagination spring-data-jpa

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

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

例如,如果给出"code"参数而不是null,则查询变为"select*from USERS where code =:code";

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

我怎样才能做到这一点?

Ala*_*Hay 15

使用QueryDSL在Spring数据中很容易做到(作为标准API的替代).使用QueryDSLPredicateExecutor的以下方法开箱即用,如果不应用任何限制,您可以将null作为谓词传递:

Page<T> findAll(com.mysema.query.types.Predicate predicate,
                Pageable pageable)
Run Code Online (Sandbox Code Playgroud)

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

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

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