In all the add, delete, change and check operation, search is the most commonly used database operation, and list query is the most, for list query can not open data paging, using MyBatis-Plus for our package good paging plug-in can quickly achieve this function.

MyBatis – Plus configuration

In Article 01 we configured the MyBatisPlusConfig class, just add a page interceptor to it:

@Bean
public PaginationInterceptor paginationInterceptor(a) {
    return new PaginationInterceptor();
}
Copy the code

List return class

For paged interfaces, our return format is as follows:

{
  "code": 200."msg": "ok"."data": {  
    "list": []."page": 1."limit": 5."total": 10."pages": 2."has_more": true}}Copy the code

So you need to customize a paginated return class:

package com.foxescap.wxbox.common;

import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.Data;

import java.util.List;

/ * * *@author xfly
 * @param <T>
 */
@Data
public class ApiResponsePage<T> {

    private List<T> list;

    private Long page;

    private Long limit;

    private Long total;

    private Long pages;

    private Boolean hasMore;

    /** * IPage convert cost object *@paramIPage paging instance *@returnReturns the * /
    public ApiResponsePage<T> convert(IPage<T> iPage) {
        this.list = iPage.getRecords();
        this.page = iPage.getCurrent();
        this.limit = iPage.getSize();

        if (iPage.isSearchCount()) {
            this.total = iPage.getTotal();
            this.pages = iPage.getPages();
            this.hasMore = this.pages > this.page;
        } else {
            this.hasMore = this.list.size() >= this.limit;
        }

        return this; }}Copy the code

Then our Service layer adds a list query method:

public ApiResponsePage<UserDto> list(String username, Integer page, Integer limit) {
    var query = lambdaQuery();
    if (username.length() > 0) {
        query = query.likeRight(User::getUsername, username);
    }
    var iPage = query.orderByDesc(User::getId)
        .page(new Page<User>(page, limit).setSearchCount(false))
        .convert(e -> modelMapper.map(e, UserDto.class));
    return new ApiResponsePage<UserDto>().convert(iPage);
}
Copy the code