Mybatis-plus分页增强、查询增强

一、分页插件

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;
    }
}

二、分页插件基础使用方式

    //    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;
    }

在上面的代码中,实际上查询结果result和参数page是同一个Page对象。

直接使用Page对象会为我们带来一些不便,项目中我们往往想要以自定义的结构返回数据,这时候只需要page对象的中某几项,而要想将page对象数据以自定义的Vo传回前端,就要在各个接口频繁赋值,非常不优雅。

三、分页增强

1、请求参数,如要增加条件,可继承这两个基类。

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、返回结果定义

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、增强Page类

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;
    }
}

代码中的Streams.map函数是自定义工具函数,用于将一个Collection对象转化为对应类型的List,因为我们需要将查出来的Po对象转化为我们所要返回的Vo对象。

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());
    }
}

四、增强Wrapper

通常我们在做模糊查询的时候,不会仅对一个字段进行模糊查询,那么在我们编写时就得写很多次.or().like(),不优雅。

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;
    }
}

五、这时候我们的使用方式如下:

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);
    }
}

附一个Mybatis-plus学习网址:https://www.hxstrive.com/subject/mybatis_plus/300.htm

猜你喜欢

转载自blog.csdn.net/qq_33235279/article/details/129749934