Mybatis-plus paging enhancement, query enhancement

1. Pagination plug-in

package com.example.jiakao.common.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@MapperScan("com.example.jiakao.mapper")
public class MyBatisPlusConfig {
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.POSTGRE_SQL));
        return interceptor;
    }
}

2. Basic usage of pagination plug-in

    //    mybatis-plus分页查询
    @GetMapping("/pagePlus")
    public IPage<Users> findPagePLus(@RequestParam int pageNum,@RequestParam int pageSize,@RequestParam(defaultValue = "") String username) {
        IPage<Users> page = new Page<>(pageNum,pageSize);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("username",username);
        Page<Users> result = usersService.page(page,queryWrapper);
        return result;
    }

In the above code, the query result result and the parameter page are actually the same Page object.

Using the Page object directly will bring us some inconvenience. In projects, we often want to return data with a custom structure. At this time, only a few items in the page object are needed, and if we want to use the custom Vo When it is sent back to the front end, it is necessary to frequently assign values ​​​​in each interface, which is very inelegant.

3. Pagination Enhancement

1. Request parameters, if you want to add conditions, you can inherit these two base classes.

package com.example.jiakao.pojo.vo.req.query;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

@Data
@ApiModel("不带关键字的分页请求参数")
public class PageReqVo {
    @ApiModelProperty(value = "请求分页数据的每页条数", required = true)
    private Long pageSize;
    @ApiModelProperty(value = "请求页码", required = true)
    private Long pageNum;
}
package com.example.jiakao.pojo.vo.req.query;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;

@EqualsAndHashCode(callSuper = true)
@Data
@ApiModel("带关键字的分页请求参数")
public class KeywordReqVo extends PageReqVo{
    @ApiModelProperty(value = "模糊查询的值")
    private String keyword;
}

2. Return result definition

package com.example.jiakao.pojo.vo.json;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import java.util.List;

@Data
@ApiModel("分页数据实体")
public class PageVo<T> {
//    条数
    @ApiModelProperty("总条数")
    private Long total;
    @ApiModelProperty("每页条数")
    private Long pageSize;
    @ApiModelProperty("当前页码")
    private Long pageNum;
    @ApiModelProperty("总页数")
    private Long pages;
    @ApiModelProperty("请求页数据")
    private List<T> list;
}

3. Enhance the Page class

package com.example.jiakao.common.enhance;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.jiakao.common.util.Streams;
import com.example.jiakao.pojo.vo.json.PageVo;
import com.example.jiakao.pojo.vo.req.query.PageReqVo;

import java.util.function.Function;

public class MpPage<Po> extends Page<Po> {
    public MpPage(PageReqVo query) {
        super(query.getPageNum(),query.getPageSize());
    }
    public PageVo<Po> buildVo(){
        PageVo<Po> pageVo = new PageVo<>();
        pageVo.setTotal(this.getTotal());
        pageVo.setPageNum(this.getCurrent());
        pageVo.setList(this.getRecords());
        pageVo.setPageSize(this.getSize());
        pageVo.setPages(this.getPages());
        return pageVo;
    }
    public <Vo> PageVo<Vo> buildVo(Function<Po, Vo> fun){
        PageVo<Vo> pageVo = new PageVo<>();
        pageVo.setTotal(this.getTotal());
        pageVo.setPageNum(this.getCurrent());
        pageVo.setList(Streams.map(this.getRecords(), fun));
        pageVo.setPageSize(this.getSize());
        pageVo.setPages(this.getPages());
        return pageVo;
    }
}

The Streams.map function in the code is a custom tool function, which is used to convert a Collection object into a corresponding type of List, because we need to convert the detected Po object into the Vo object we want to return.

package com.example.jiakao.common.util;

import java.util.Collection;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

public class Streams {
    public static <T, R> List<R> map(Collection<T> list, Function<T, R> fun){
        return list.stream().map(fun).collect(Collectors.toList());
    }
}

4. Enhance Wrapper

Usually when we do fuzzy query, we don’t just perform fuzzy query on one field, so when we write, we have to write .or().like() many times, which is not elegant.

package com.example.jiakao.common.enhance;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;

public class MpLambdaQueryWrapper<T> extends LambdaQueryWrapper<T> {
    public MpLambdaQueryWrapper<T> likes(Object val, SFunction<T, ?>... funcs){
        if(val == null) return this;
        String str = val.toString();
        if(str.length() <= 0) return this;
//        nested() 方法添加嵌套 SQL
        nested( (wrapper) -> {
            for (SFunction<T, ?> func : funcs) {
                wrapper.like(func, str).or();
            }
        });
        return this;
    }
}
package com.example.jiakao.common.enhance;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.util.ObjectUtils;

public class MpQueryWrapper<T> extends QueryWrapper<T> {
    public MpQueryWrapper<T> likes(Object val, String... culumns){
        if(val == null) return this;
        String str = val.toString();
        if(str.length() <= 0) return this;
//        nested() 方法添加嵌套 SQL
        nested( (wrapper) -> {
            for (String column : culumns) {
                if(!ObjectUtils.isEmpty(column)){
                    wrapper.like(column, str).or();
                }
            }
        });
        return this;
    }
}

5. At this time, our usage is as follows:

package com.example.jiakao.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.jiakao.common.enhance.MpPage;
import com.example.jiakao.common.enhance.MpQueryWrapper;
import com.example.jiakao.common.mapStruct.MapStructs;
import com.example.jiakao.mapper.UsersMapper;
import com.example.jiakao.pojo.entity.UsersPo;
import com.example.jiakao.pojo.vo.json.PageVo;
import com.example.jiakao.pojo.vo.list.UserVo;
import com.example.jiakao.pojo.vo.req.query.KeywordReqVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class UsersService extends ServiceImpl<UsersMapper, UsersPo> {
    public PageVo<UserVo> page(KeywordReqVo query){
        MpPage<UsersPo> page = new MpPage<>(query);
        MpQueryWrapper<UsersPo> wrapper = new MpQueryWrapper<>();
        wrapper.likes(query.getKeyword(), "username");
        return page(page,wrapper).buildVo(MapStructs.INSTANCE::po2vo);
    }
}

Attach a Mybatis-plus learning URL: https://www.hxstrive.com/subject/mybatis_plus/300.htm

Guess you like

Origin blog.csdn.net/qq_33235279/article/details/129749934