具有分页功能的Spring自定义查询 [英] Spring Custom Query with pageable

查看:79
本文介绍了具有分页功能的Spring自定义查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Spring应用程序中实现分页.我知道使用存储库可以实现分页,但是我们无法编写自己的查询来进行数据检索,因为存储库中的方法有限,也没有方法接受查询类.

I want to to implement pagination in spring application.I know using repository we can implement pagination but we can not write our own query for data retrieve there are limited methods in repository that too there is no method accepting query class.

如果我们要编写自定义查询以从mongodb中检索数据,则必须使用mongotemaplete,正如我所知,使用mongotemplate我们无法实现分页.

If we want to write our custom query to retrieve data from mongodb we have to use mongotemaplete, as i know with mongotemplate we can not implement pagination.

还有其他方法可以与数据库查询一起实现分页. 任何人都可以帮助我.

Is there any another way to implement pagination along with db queries. any one can help me.

推荐答案

如您所知,MongoTemplate不支持完整的页面抽象.就像KneeLess所说的那样,您可以使用@Query -Annotation进行一些自定义查询.

As you figured out, MongoTemplate doesn't support the complete page abstraction. Like KneeLess said you can use the @Query-Annotation to do some custom queries.

如果这还不够,可以将Spring Repository PageableExecutionUtils与MongoTemplate结合使用.

In case this isn't enough for you, can use utilize the Spring Repository PageableExecutionUtils in combination with your MongoTemplate.

例如这样的

@Override
public Page<XXX> findSophisticatedXXX(/* params, ... */ @NotNull Pageable pageable) {

    Query query = query(
            where("...")
            // ... sophisticated query ...
    ).with(pageable);

    List<XXX> list = mongoOperations.find(query, XXX.class);
    return PageableExecutionUtils.getPage(list, pageable,
              () -> mongoOperations.count((Query.of(query).limit(-1).skip(-1), XXX.class));
}

Spring Repository也在做同样的事情.如您所见

Spring Repositories are doing the same. As you can see here, they fire two queries as well.

这篇关于具有分页功能的Spring自定义查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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