springboot整合mybatis-plus

Mybatis-Plus(简称MP)是一个 Mybatis 的增强工具,在 Mybatis 的基础上只做增强不做改变,为简化开发、提高效率而生。

特性:

  • 无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑

  • 损耗小:启动即会自动注入基本 CURD,性能基本无损耗,直接面向对象操作

  • 强大的 CRUD 操作:内置通用 Mapper、通用 Service,仅仅通过少量配置即可实现单表大部分 CRUD 操作,更有强大的条件构造器,满足各类使用需求

  • 支持主键自动生成:支持多达 4 种主键策略(内含分布式唯一 ID 生成器 - Sequence),可自由配置,完美解决主键问题

  • 内置代码生成器:采用代码或者 Maven 插件可快速生成 Mapper 、 Model 、 Service 、 Controller 层代码,支持模板引擎,更有超多自定义配置等您来使用

  • 内置分页插件:基于 MyBatis 物理分页,开发者无需关心具体操作,配置好插件之后,写分页等同于普通 List 查询

  • 分页插件支持多种数据库:支持 MySQL、MariaDB、Oracle、DB2、H2、HSQL、SQLite、Postgre、SQLServer 等多种数据库

1.环境搭建

1 配置druid.datasource数据源,获取数据库连接

pom.xml导入依赖:


    org.springframework.boot
    spring-boot-starter-jdbc


    com.alibaba
    druid-spring-boot-starter
    1.2.8


    mysql
    mysql-connector-java
    5.1.49

yml文件配置

spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/j220501?useUnicode=true&characterEncoding=utf8&useSSL=false
    username: root
    password: YOGr1hAd5Yi65JlFGKdVv010LaxT1M3SfDdSQ9Gqso6ccHAL5fxfjzlon0B8BPLfzEGz0llw97dXfIK8YDs8qw==
    druid:
      initial-size: 1
      min-idle: 3
      max-active: 20
      # 配置获取连接等待超时的时间
      max-wait: 60000
      # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
      time-between-eviction-runs-millis: 60000
      # 配置一个连接在池中最小生存的时间,单位是毫秒
      min-evictable-idle-time-millis: 30000
      validation-query: select 'x'
      test-while-idle: true
      #建议配置为false。获取连接时执行validationQuery检测连接是否有效,这个配置会降低性能
      test-on-borrow: false
      #建议配置为false。获取连接时执行validationQuery检测连接是否有效,这个配置会降低性能
      test-on-return: false
      # 打开PSCache,并且指定每个连接上PSCache的大小
      pool-prepared-statements: true
      max-pool-prepared-statement-per-connection-size: 20
      #配置监控统计拦截的filters,去掉后监控界面sql无法统计
      filters: config,stat,slf4j
      # 通过connectProperties属性来打开mergeSql功能;慢SQL记录
      connection-properties: ruid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000;config.decrypt=true;config.decrypt.key=MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAM1CwAKEYnsOsT44An+pEBJM+uFh7/kmftHZz44ZiwfX6eJX4jxSiR9XF3KJZUwLrdN7twz08y557+yg4/EPaLMCAwEAAQ==
      # 合并多个DruidDataSource的监控数据
      use-global-data-source-stat: true
      #采集数据库监控的数据
      web-stat-filter:
        url-pattern: /*
        enabled: true
        exclusions: .js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*
      #展示监控信息
      stat-view-servlet:
        url-pattern: /druid/*
        allow: 127.0.0.1
        reset-enable: false
        #是否开启,设置为true才能打开监控页面
        enabled: true
        #druid监控登录页面的用户名
        login-username: root
        #druid监控登录页面的密码
        login-password: root

2.配置mybatis-plus

pom.xml引入依赖

	
        
            com.baomidou
            mybatis-plus-boot-starter
            3.3.2
        
        
        
            com.baomidou
            mybatis-plus-generator
            3.3.2
        
        
        
            org.freemarker
            freemarker
            2.3.28
        

yml文件配置

mybatis-plus:
  mapper-locations: classpath*:com/hqyj/*/*/mapper/*Mapper.xml
  type-aliases-package: com.hqyj.*.*.entity
  global-config:
    db-config:
      #主键类型 AUTO:"数据库ID自增" INPUT:"用户输入ID",ASSIGN_ID:"mybatisplus分配ID,Long,Integer,String", ASSIGN_UUID:"分配UUID,String";
      id-type: auto
      #字段策略 IGNORED:"忽略判断"  NOT_NULL:"非 NULL 判断")  NOT_EMPTY:"非空判断"
      #filed-strategy在高版本被废弃(3.1.2以后)
      #filed-strategy: NOT_EMPTY
      insert-strategy: not_empty
      select-strategy: not_empty
      update-strategy: not_empty
      #刷新mapper 调试神器
      refresh-mapper: true
      #逻辑删除配置
      logic-delete-value: 1
      logic-not-delete-value: 0
  configuration:
  	#驼峰下划线转换
    map-underscore-to-camel-case: true
    cache-enabled: false

3.代码生成器

创建CodeGenerator类:

public class CodeGenerator {

    /**
     * 

* 读取控制台内容 *

*/ public static String scanner(String tip) { Scanner scanner = new Scanner(System.in); StringBuilder help = new StringBuilder(); help.append("请输入" + tip + ":"); System.out.println(help.toString()); if (scanner.hasNext()) { String ipt = scanner.next(); if (!StringUtils.isEmpty(ipt)) { return ipt; } } throw new MybatisPlusException("请输入正确的" + tip + "!"); } public static void main(String[] args) { // 代码生成器 AutoGenerator mpg = new AutoGenerator(); // 全局配置 GlobalConfig gc = new GlobalConfig(); // String projectPath = System.getProperty("user.dir"); // gc.setOutputDir(projectPath + "/src/main/java"); String projectPath = "D://mybatisCode"; gc.setOutputDir(projectPath); gc.setAuthor("sdx2009"); //设置完之后是否打开资源管理器 gc.setOpen(false); gc.setSwagger2(false); gc.setIdType(IdType.AUTO); //设置是否覆盖原始生成的文件 gc.setFileOverride(true); gc.setActiveRecord(false);// 不需要ActiveRecord特性的请改为false gc.setEnableCache(false);// XML 二级缓存 gc.setBaseResultMap(true);// XML ResultMap gc.setBaseColumnList(true);// XML columList //去掉service的i前缀 gc.setServiceName("%sService"); mpg.setGlobalConfig(gc); // 数据源配置 DataSourceConfig dsc = new DataSourceConfig(); dsc.setDbType(DbType.MYSQL); dsc.setDriverName("com.mysql.jdbc.Driver"); dsc.setUsername("root"); dsc.setPassword("123456"); dsc.setUrl( "jdbc:mysql://127.0.0.1:3306/j220501?useUnicode=true&characterEncoding=utf8"); mpg.setDataSource(dsc); // 包配置 PackageConfig pc = new PackageConfig(); pc.setModuleName("user");// 模块名 pc.setParent("com.hqyj.springbootdemo01"); mpg.setPackageInfo(pc); // 自定义配置 InjectionConfig cfg = new InjectionConfig() { @Override public void initMap() { // to do nothing } }; List focList = new ArrayList<>(); focList.add(new FileOutConfig("/templates/mapper.xml.ftl") { @Override public String outputFile(TableInfo tableInfo) { // 自定义输入文件名称 return projectPath + "/src/main/resources/mapper/" + pc.getModuleName() + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML; } }); cfg.setFileOutConfigList(focList); mpg.setCfg(cfg); mpg.setTemplate(new TemplateConfig().setXml(null)); // 策略配置 StrategyConfig strategy = new StrategyConfig(); strategy.setTablePrefix(new String[]{""});// 此处可以修改为您的表前缀 strategy.setNaming(NamingStrategy.underline_to_camel); // strategy.setColumnNaming(NamingStrategy.underline_to_camel); // strategy.setSuperEntityClass("com.baomidou.ant.common.BaseEntity"); strategy.setRestControllerStyle(true); // strategy.setSuperControllerClass("com.baomidou.ant.common.BaseController"); strategy.setInclude("user");// 表名 // strategy.setSuperEntityColumns("id"); // strategy.setControllerMappingHyphenStyle(true); // strategy.setTablePrefix(pc.getModuleName() + "_"); strategy.setEntityTableFieldAnnotationEnable(true); // strategy.setLogicDeleteFieldName("del_flag"); //设置是否启用Lombok strategy.setEntityLombokModel(true); List tableFillList = new ArrayList(); TableFill tableFill1 = new TableFill("create_time", FieldFill.INSERT); TableFill tableFill2 = new TableFill("creator", FieldFill.INSERT); TableFill tableFill3 = new TableFill("update_time", FieldFill.UPDATE); TableFill tableFill4 = new TableFill("operator", FieldFill.UPDATE); tableFillList.add(tableFill1); tableFillList.add(tableFill2); tableFillList.add(tableFill3); tableFillList.add(tableFill4); strategy.setTableFillList(tableFillList); mpg.setStrategy(strategy); mpg.setTemplateEngine(new FreemarkerTemplateEngine()); mpg.execute(); } }

修改相关配置后,运行即可产生代码文件,产生的代码文件包含:

*Mapper.xml、entity实体类、mapper类、service接口、service实现类、controller

将以上文件拷贝到项目相应的目录下即可。

自动填充处理器:

创建handler层

package com.hqyj.j220701.springboot.springbootdemo01.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        Object createTime = getFieldValByName("createTime", metaObject);
        if (null == createTime){
            setFieldValByName("createTime", LocalDateTime.now(),metaObject);
        }
        Object creator = getFieldValByName("creator", metaObject);
        if (null == creator){
            setFieldValByName("creator","system",metaObject);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        Object updateTime = getFieldValByName("updateTime", metaObject);
        if (null == updateTime){
            setFieldValByName("updateTime", LocalDateTime.now(),metaObject);
        }
        Object operator = getFieldValByName("operator", metaObject);
        if (null == operator){
            setFieldValByName("operator","system",metaObject);
        }
    }
}

2.数据操作

条件构造器 

springboot整合mybatis-plus_第1张图片

 以下操作均在serverImpl实现类上实现

1.保存数据(添加数据)

单条保存: this.save();

批量保存:  this.saveBatch();

2.修改数据

根据id修改: this.updateById();

通过创建updatewrapper对象作为条件修改:

@Override
    public boolean updateUser(Integer id, String userName, String password) {
        User user = new User();
        user.setUserName(userName);
        user.setPassword(password);
        UpdateWrapper wrapper = new UpdateWrapper<>();
        wrapper.eq("id", id);
        return this.update(user, wrapper);
    }

批量修改:

@Override
    public boolean updateUser(Integer id, String userName, String password) {
        User user = new User();
        user.setUserName(userName);
        user.setPassword(password);
        user.setId(id);
        List userList = new ArrayList<>();
        userList.add(user);
        return this.updateBatchById(userList);
    }

3.查询数据

条件查询

@Override
    public User getUser(String userName, String password) {
        QueryWrapper wrapper = new QueryWrapper<>();
        wrapper.eq("user_name", userName);
        wrapper.eq("password",password);
        return this.getOne(wrapper);
    }

相当于:WHERE (user_name = ? AND password = ?)

and与or组合查询:

@Override
    public User getUser(String userName, String password) {
        QueryWrapper wrapper = new QueryWrapper<>();
        wrapper.eq("user_name", userName);
        wrapper.eq("password", password);
        wrapper.and(w -> w.eq("user_name", userName).or().eq("password", password));
        return this.getOne(wrapper);
    }

相当于:

WHERE (user_name = ? AND password = ? AND (user_name = ? OR password = ?))

分页查询

@Override
    public Page getPageUser(Integer pageNumber, Integer pageSize, String userName,
                                  String password) {
      	//分页信息
        Page page = new Page<>();
      	//每页多少条数据
        page.setSize(pageSize);
      	//第几页
        page.setCurrent(pageNumber);

      	//筛选条件
        QueryWrapper wrapper = new QueryWrapper<>();
        wrapper.eq("user_name", userName);
        wrapper.eq("password", password);
      
        return this.page(page, wrapper);
    }

 分页查询需使用泛型返回结果对象

创建Result类

@Data
public class Result {
    private Integer code;

    private String msg;

    private T data;

    /**
     * 返回成功
     *
     * @return
     */
    public Result success() {
        return success("操作成功!");
    }

    public Result success(String message) {
        return success(200, message);
    }

    public Result success(Integer code, String message) {
        this.setCode(code);
        this.setMsg(message);
        return this;
    }

    public Result put(T obj) {
        this.setData(obj);
        return this;
    }

    /**
     * 返回失败
     *
     * @param code
     * @param message
     * @return
     */

    public Result error(Integer code, String message) {
        return success(code, message);
    }

    public Result error(String message) {
        return error(500, message);
    }

    public Result error() {
        return error("操作失败!");
    }
}

在controller中使用Result作为返回对象

@GetMapping("/info")
    public Result getUser(String userName, String password) {
        User user = userService.getUser(userName, password);
        return new Result<>().success().put(user);
    }

解决MybatisPlus中page的total为0及未分页的问题:添加分页插件

@Configuration
public class MybatisPlusPaginationConfig {

    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        return paginationInterceptor;
    }
}

泛型分页查询结果返回对象:

@Data
public class PageResult {

    private Integer code;

    private String msg;

    private Long total;

    private Long totalPage;

    private Long pageNumber;

    private List rows;

    /**
     * 默认构造方法
     */
    public PageResult() {

    }

    public PageResult(Long total, List rows, Long pageNumber, Long pageSize) {
        this.total = total;
        this.rows = rows;
        this.pageNumber = pageNumber;
        this.code = 200;
        this.msg = "";
        Long totalPage = total / pageSize;
        if (total % pageSize > 0) {
            totalPage++;
        }
        this.totalPage = totalPage;
    }
}

在controller中统一使用PageResult对象作为返回对象:

@GetMapping("/page")
    public PageResult getPageUser(Integer pageNumber, Integer pageSize, String userName,
                                         String password) {
        Page page = userService.getPageUser(pageNumber, pageSize, userName, password);
        PageResult result = new PageResult<>(page.getTotal(), page.getRecords());
        return result;
    }

 多表查询

4.删除数据

 根据id删除:this.removeById();

3.综合实现

实现单表的增删改分页以及多表查询

①首先需要创建2个结果类:Result,PageResult

Result类:

抽取controller层的逻辑判断成一个单独类,判断service层方法的成功与失败

package com.hqyj.j220701.springboot.springbootdemo01.common.result;

import lombok.Data;

import java.io.Serializable;

@Data
public class Result implements Serializable {
    private Integer code;
    private String msg;
    private  T data;

    public Result() {
    }

    public Result(Integer code, String msg, T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    //如果成功,返回成功的方法,
    public Result success(Integer code,String msg){
        this.code = code;
        this.msg = msg;
        return this;
    }

    public Result success(String msg){
        return success(200,msg);
    }

    public Result success(){
        return success("操作成功");
    }

    public Result put(T data){
        this.data = data;
        return this;
    }

//    失败返回失败的方法
public Result error(Integer code,String msg){
    this.code = code;
    this.msg = msg;
    return this;
}

    public Result error(String msg){
        return error(500,msg);
    }

    public Result error(){
        return error("操作失败");
    }


}

PageResult类:

分页公共结果类,设置页面展示参数

package com.hqyj.j220701.springboot.springbootdemo01.common.result;

import lombok.Data;

import java.io.Serializable;
import java.util.List;

@Data
public class PageResult implements Serializable {
    private Integer code;
    private String msg;
    private List list;
    private Long pageNumber;
    private Long pageSize;
    private Long total;
    private Long totalPage;

    public PageResult(Long totalPage, Long pageNumber, Long pageSize, Long total, List list) {

        this.list = list;
        this.pageNumber = pageNumber;
        this.pageSize = pageSize;
        this.total = total;
        this.totalPage = totalPage;
    }
}

②创建entity实体类联系数据库,创建dto层联系前端

user实体类(由代码生成器生成)

package com.hqyj.j220701.springboot.springbootdemo01.user.entity;

import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;
import lombok.EqualsAndHashCode;

import java.io.Serializable;
import java.time.LocalDateTime;

/**
 * 

* *

* * @author sdx2009 * @since 2022-09-22 */ @Data @EqualsAndHashCode(callSuper = false) @TableName("user") public class User implements Serializable { private static final long serialVersionUID = 1L; //主键 @TableId(value = "id", type = IdType.AUTO) private Integer id; @TableField("user_name") private String userName; @TableField("password") private String password; @TableField("sex") private String sex; @TableField("age") private Integer age; @TableField(value = "create_time", fill = FieldFill.INSERT) private LocalDateTime createTime; @TableField(value = "creator", fill = FieldFill.INSERT) private String creator; @TableField(value = "update_time", fill = FieldFill.UPDATE) private LocalDateTime updateTime; @TableField(value = "operator", fill = FieldFill.UPDATE) private String operator; }

在dto层,分别创建3个信息类

QueryUser:查询用户与前端交互实现分页

package com.hqyj.j220701.springboot.springbootdemo01.user.dto;

import lombok.Data;

@Data
public class QueryUser {
    private Integer pageNumber;
    private Integer pageSize;
    private String userName;
    private String password;
    private String sex;
    private Integer age;
    private Integer id;
}

UserInfo:只对用户信息基础操作

package com.hqyj.j220701.springboot.springbootdemo01.user.dto;

import lombok.Data;

@Data
public class UserInfo {
    private String userName;
    private String password;
    private String sex;
    private Integer age;
    private Integer id;
}

UserRole:多表查询

package com.hqyj.j220701.springboot.springbootdemo01.user.dto;

import lombok.Data;

@Data
public class UserRole {
    private Integer userId;
    private String userName;
    private Integer roleId;
    private String roleCode;
    private String roleName;
}

③编写多表查询的sql

在resources下的mapper.xml中编写





    
    
        
        
        
        
        
        
        
        
        
    

    
    
        id, user_name, password, sex, age, create_time, creator, update_time, operator
    

    

④在controller层编写增删改操作

package com.hqyj.j220701.springboot.springbootdemo01.user.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hqyj.j220701.springboot.springbootdemo01.common.result.PageResult;
import com.hqyj.j220701.springboot.springbootdemo01.common.result.Result;
import com.hqyj.j220701.springboot.springbootdemo01.user.dto.QueryUser;
import com.hqyj.j220701.springboot.springbootdemo01.user.dto.UserInfo;
import com.hqyj.j220701.springboot.springbootdemo01.user.dto.UserRole;
import com.hqyj.j220701.springboot.springbootdemo01.user.entity.User;
import com.hqyj.j220701.springboot.springbootdemo01.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController//以json字符串返回结果
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/add")
    public Result addUser(@RequestBody UserInfo userInfo){
        boolean result = userService.addUser(userInfo);
        if (result){
            return new Result<>().success().put(result);
        }else {
            return new Result<>().error();
        }
    }

    @PostMapping("/update")
    public Result updateUser(@RequestBody UserInfo userInfo){
        boolean result = userService.updateUser(userInfo);
        if (result){
            return new Result<>().success().put(result);
        }else {
            return new Result<>().error();
        }
    }

    @GetMapping("/delete")
    public Result deleteUser(@RequestParam Integer id){
        boolean result = userService.deleteUser(id);
        if (result){
            return new Result<>().success().put(result);
        }else {
            return new Result<>().error();
        }
    }

    @GetMapping("/page")
    public PageResult getUserPage(QueryUser queryUser){
         Page page = userService.getUserPage(queryUser);

         PageResult result = new PageResult(page.getCurrent(),page.getSize(),
                 page.getTotal(),page.getPages(),page.getRecords());
         result.setCode(200);

         return result;

    }

//多表查询
    @GetMapping("/list/v2")
    public Result getUserListV2(UserInfo userInfo){

       List list = userService.getUserListV2(userInfo);

       if (CollectionUtils.isEmpty(list)){
           return new Result<>().error();
       }
        return new Result<>().success().put(list);
    }
//多表分页查询
    @GetMapping("/page/v2")
    public PageResult getUserPageV2(QueryUser queryUser){
        Page list = userService.getUserPageV2(queryUser);
        PageResult result = new PageResult<>(list.getCurrent(),list.getSize(),
                list.getTotal(),list.getPages(),list.getRecords());
        result.setCode(200);
        return result;

    }

}

⑤在service服务层实现方法

接口类

package com.hqyj.j220701.springboot.springbootdemo01.user.service;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.hqyj.j220701.springboot.springbootdemo01.user.dto.QueryUser;
import com.hqyj.j220701.springboot.springbootdemo01.user.dto.UserInfo;
import com.hqyj.j220701.springboot.springbootdemo01.user.dto.UserRole;
import com.hqyj.j220701.springboot.springbootdemo01.user.entity.User;

import java.util.List;

/**
 * 

* 服务类 *

* * @author sdx2009 * @since 2022-09-22 */ public interface UserService extends IService { boolean addUser(UserInfo userInfo); boolean updateUser(UserInfo userInfo); boolean deleteUser(Integer id); List getUserList(QueryUser queryUser); Page getUserPage(QueryUser queryUser); List getUserListV2(UserInfo userInfo); Page getUserPageV2(QueryUser queryUser); }

实现类

package com.hqyj.j220701.springboot.springbootdemo01.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hqyj.j220701.springboot.springbootdemo01.user.dto.QueryUser;
import com.hqyj.j220701.springboot.springbootdemo01.user.dto.UserInfo;
import com.hqyj.j220701.springboot.springbootdemo01.user.dto.UserRole;
import com.hqyj.j220701.springboot.springbootdemo01.user.entity.User;
import com.hqyj.j220701.springboot.springbootdemo01.user.mapper.UserMapper;
import com.hqyj.j220701.springboot.springbootdemo01.user.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 

* 服务实现类 *

* * @author sdx2009 * @since 2022-09-22 */ @Service public class UserServiceImpl extends ServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Override public boolean addUser(UserInfo userInfo) { User user = new User(); BeanUtils.copyProperties(userInfo, user); return this.save(user); } @Override public boolean updateUser(UserInfo userInfo) { User user = new User(); BeanUtils.copyProperties(userInfo, user); return this.updateById(user); } @Override public boolean deleteUser(Integer id) { return this.removeById(id); } @Override public List getUserList(QueryUser queryUser) { QueryWrapper wrapper = new QueryWrapper<>(); // 相当于user_name=#{userName} /* wrapper.eq("user_name",queryUser.getUserName()); wrapper.eq("password",queryUser.getPassword()); wrapper.lt("age",queryUser.getAge()); // OR sex LIKE %sex% wrapper.or().like("sex",queryUser.getSex());*/ // userName = #{userName} AND (password=#{password} OR sex LIKE %sex%) wrapper.eq("user_name", queryUser.getUserName()). and(w -> w.eq("password", queryUser.getPassword()). or().like("sex", queryUser.getSex())); return this.list(wrapper); } @Override public Page getUserPage(QueryUser queryUser) { // page对象中的current默认为1,如果参数中的pageNumber<=1,则page对象按照current=1分页 Page page = new Page<>(); page.setCurrent(queryUser.getPageNumber()); page.setSize(queryUser.getPageSize()); //TODO 带条件查询的操作 // 按密码查询 QueryWrapper wrapper = new QueryWrapper<>(); if (null != queryUser.getPassword()) { wrapper.eq("password", queryUser.getPassword()); } return this.page(page,wrapper); } // 多表查询 @Override public List getUserListV2(UserInfo userInfo) { Map params = new HashMap<>(); params.put("userName",userInfo.getUserName()); List list = userMapper.selectUserList(params); return list; } @Override public Page getUserPageV2(QueryUser queryUser) { Page page = new Page<>(); page.setCurrent(queryUser.getPageNumber()); page.setSize(queryUser.getPageSize()); Map params = new HashMap<>(); params.put("userName",queryUser.getUserName()); return userMapper.selectUserList(page,params); } }

⑥最后在mapper层实现多表查询的方法对应xml文件

package com.hqyj.j220701.springboot.springbootdemo01.user.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hqyj.j220701.springboot.springbootdemo01.user.dto.UserRole;
import com.hqyj.j220701.springboot.springbootdemo01.user.entity.User;
import org.apache.ibatis.annotations.Param;

import java.util.List;
import java.util.Map;

/**
 * 

* Mapper 接口 *

* * @author sdx2009 * @since 2022-09-22 */ public interface UserMapper extends BaseMapper { List selectUserList(@Param("params") Map params); Page selectUserList(Page page,@Param("params") Map params); }

可以使用postman调试接口。

你可能感兴趣的:(springboot,mybatis,spring,boot,java)