简体   繁体   English

Spring 分页和计数查询

[英]Spring Pagination and count query

I'm developping a REST API managing Module objects.我正在开发一个 REST API 管理Module对象。 For the UI, I need pagination and the total number of pages.对于 UI,我需要分页和总页数。

I know when Spring uses Page<T> an additional count query is used (to get the total number of pages) which is an overhead cost.我知道当 Spring 使用Page<T>时,会使用额外的计数查询(以获取总页数),这是一项间接费用。

I need this total number of pages for the UI.我需要 UI 的总页数。 But only once (no need to execute again the count query for each new page).但只有一次(不需要为每个新页面再次执行计数查询)。

So I was thinking of exposing two endpoints:所以我在考虑公开两个端点:

  • getting the total number of elements获取元素总数
  • getting the data (so I'm returning a List<Module> instead of Page<Module> because I don't want to execute this extra count query for each page request)获取数据(所以我返回一个List<Module>而不是Page<Module>因为我不想为每个页面请求执行这个额外的计数查询)

Something like this:是这样的:

@RestController @RestController

@RequestMapping("/api/modules")
public class ModuleApi {

    private final ModuleService service;

    @GetMapping("/count")
    public Long count() {
        return service.countModules();
    }


    @GetMapping
    public List<Module> find( 
                @RequestParam("name") String name ,
                @RequestParam(value = "page", required = false, defaultValue = "0") Integer page,
                @RequestParam(value = "size", required = false, defaultValue = "10") Integer size
    ) {
        return service.find(PageRequest.of(page, size));
    }
}

Is this a good design?这是一个好的设计吗?

Counting once means your count will get outdated as more Modules are inserted into your database in which case the count is no longer relevant.计数一次意味着您的计数将随着更多模块插入您的数据库而过时,在这种情况下计数不再相关。

The better design would be to work with spring's Slice<Module> , forget the count altogether, and implement the solution on the front end side.更好的设计是使用 spring 的Slice<Module> ,完全忘记计数,并在前端实现解决方案。 Think of how some sites only fetch you more results when you are at the bottom of the page.想一想某些网站如何仅在您位于页面底部时才能为您带来更多结果。

However this may cost a lot of effort and time on your architecture so your proposal should be fine.然而,这可能会在您的架构上花费大量的精力和时间,因此您的建议应该没问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM