目录
四、Mybatisplus中使用Mybatis实现多表联查功能
构建一个springboot项目,勾上这五个组件,如图所示:

我们勾选好了的,在application.properties里面都自动配置好了,我们用我们yml进行转换为树形

解决方案:就是降低版本

pom依赖
mysql
mysql-connector-java
5.1.44


application.yml
mybatis:
mapper-locations: classpath:mappers/**/*xml
type-aliases-package: com.jwj.springbootmybatis.mybatis.entity
server:
port: 8080
spring:
application:
name: springbootmybatis
datasource:
driver-class-name: com.mysql.jdbc.Driver
name: defaultDataSource
password: 123456
url: jdbc:mysql://localhost:3306/mybatis_ssm?useUnicode=true&characterEncoding=UTF-8
username: root
jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/mybatis_ssm?useUnicode=true&characterEncoding=UTF-8 jdbc.username=root jdbc.password=123456
generatorConfig.xml 改三个地方,类名要跟创建的类名保持一致,还有上面那个yml里面的mappers后加上/**,还要改对生成的位置在我创建的resource里面的mappers生成在这里面才可以
springbootmybatis.model" targetProject="src/main/java"> springbootmybatis.mapper" targetProject="src/main/resources/mappers"> springbootmybatis.mapper" targetProject="src/main/java" type="XMLMAPPER">
还要复制一个代码生成的插件。pom.xml
org.mybatis.generator
mybatis-generator-maven-plugin
1.3.2
mysql
mysql-connector-java
5.1.44
true
接下来我们代码生成一波,看看能不能生成到我们指定的目录下面

注意这里我们要微调一下,如图所示:

在我们的生成中的BookMapper.xml里面这里都可以不用写它也不会报错

利用Eolink进行测试,这里我就创建一个类来测试 BookController.java
package com.jwj.springbootmybatis.web;
import com.jwj.springbootmybatis.mapper.BookMapper;
import com.jwj.springbootmybatis.model.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
/**
* @author 敢敢
* @site www.javajwj.com
* @company xxx公司
* @create 2022-11-02 16:34
*/
@RestController
@RequestMapping("/mybatis")
public class BookController {
@Autowired
private BookMapper bookMapper;
// 查询
@GetMapping("/get")
public Book get(Integer bid){
return bookMapper.selectByPrimaryKey(bid);
}
// 删除
@DeleteMapping("/delete")
public int delete(Integer bid){
return bookMapper.deleteByPrimaryKey(bid);
}
// 新增
@PutMapping("/add")
public int add(Book book){
return bookMapper.insertSelective(book);
}
}
开启包扫描功能、开启事务管理
//完成对Mapper接口的扫描 @MapperScan({"com.jwj.springbootmybatis.mapper"})
//开启事务管理 @EnableTransactionManagement
启动类
package com.jwj.springbootmybatis;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.transaction.annotation.EnableTransactionManagement;
//完成对Mapper接口的扫描
@MapperScan({"com.jwj.springbootmybatis.mapper"})
//开启事务管理
@EnableTransactionManagement
@SpringBootApplication
public class SpringbootmybatisApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootmybatisApplication.class, args);
}
}
测试结果如图所示:其他的我就不测试了

目录结构如图所示:

官网
这里就可以去了解一下

为什么要知道mybatis-plus,它的简便语法是mp。
①企业中大量会使用到
②极大的减少*Mapper.xml中的SQL 编写
③与若依相比略微繁琐,但是可移植性极强
思考:当前所开发的项目,只需要若依中的代码生成器功能,其它功能一概不要,如何实现?
因为若依代码生成器跟若依的项目本身耦合度非常高,我们是不能移植过来的,而Mybatis-plus可以
创建一个新的springboot项目

相关配置如下:
pom.xml 中添加额外的pom依赖
com.baomidou
mybatis-plus-boot-starter
3.4.2
com.baomidou
mybatis-plus-generator
3.4.1
org.freemarker
freemarker
2.3.31
同样的把application.properties转成yml文件,这里的其实跟我们上面的mybatis的配置是差不多的
server:
port: 8080
spring:
application:
name: springbootmp
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
name: defaultDataSource
password: 123456
url: jdbc:mysql://localhost:3306/mybatis_ssm?useUnicode=true&characterEncoding=UTF-8
username: root
mybatis-plus:
mapper-locations: classpath:mappers/**/*.xml
type-aliases-package: com.zking.springbootmp.book.model

Mybatis-plus代码生成类 这个类是固定的
- package com.jwj.springbootmp.mp;
-
- import com.baomidou.mybatisplus.annotation.DbType;
- import com.baomidou.mybatisplus.annotation.IdType;
- import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
- import com.baomidou.mybatisplus.core.toolkit.StringPool;
- import com.baomidou.mybatisplus.core.toolkit.StringUtils;
- import com.baomidou.mybatisplus.generator.AutoGenerator;
- import com.baomidou.mybatisplus.generator.InjectionConfig;
- import com.baomidou.mybatisplus.generator.config.*;
- import com.baomidou.mybatisplus.generator.config.po.TableInfo;
- import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
- import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
-
- import java.util.ArrayList;
- import java.util.List;
- import java.util.Scanner;
-
- /**
- * mybatis-plus代码生成
- */
- public class MPGenerator {
-
- /**
- *
- * 读取控制台内容
- *
- */
- 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.isNotBlank(ipt)) {
- if ("quit".equals(ipt)) return "";
- return ipt;
- }
- }
- throw new MybatisPlusException("请输入正确的" + tip + "!");
- }
-
- public static void main(String[] args) {
- // 代码生成器
- AutoGenerator mpg = new AutoGenerator();
-
- // 1.全局配置
- GlobalConfig gc = new GlobalConfig();
- String projectPath = System.getProperty("user.dir") + "/testspboot03";
- System.out.println(projectPath);
-
- gc.setOutputDir(projectPath + "/src/main/java");
- gc.setOpen(false);
- gc.setBaseResultMap(true);//生成BaseResultMap
- gc.setActiveRecord(false);// 不需要ActiveRecord特性的请改为false
- gc.setEnableCache(false);// XML 二级缓存
- gc.setBaseResultMap(true);// XML ResultMap
- gc.setBaseColumnList(true);// XML columList
- //gc.setSwagger2(true); //实体属性 Swagger2 注解
- gc.setAuthor("lky");
-
- // 自定义文件命名,注意 %s 会自动填充表实体属性!
- gc.setMapperName("%sMapper");
- gc.setXmlName("%sMapper");
- gc.setServiceName("%sService");
- gc.setServiceImplName("%sServiceImpl");
- gc.setControllerName("%sController");
-
- gc.setIdType(IdType.AUTO);
- mpg.setGlobalConfig(gc);
-
- // 2.数据源配置
- DataSourceConfig dsc = new DataSourceConfig();
- dsc.setDbType(DbType.MYSQL);
- dsc.setUrl("jdbc:mysql://localhost:3306/mybatis_ssm?useUnicode=true&characterEncoding=UTF-8");
- dsc.setDriverName("com.mysql.jdbc.Driver");
- dsc.setUsername("root");
- dsc.setPassword("123456");
- mpg.setDataSource(dsc);
-
- // 3.包配置
- PackageConfig pc = new PackageConfig();
- String moduleName = scanner("模块名(quit退出,表示没有模块名)");
- if (StringUtils.isNotBlank(moduleName)) {
- pc.setModuleName(moduleName);
- }
- pc.setParent("com.zking.demo")
- .setMapper("mapper")
- .setService("service")
- .setController("controller")
- .setEntity("model");
- mpg.setPackageInfo(pc);
-
- // 4.自定义配置
- InjectionConfig cfg = new InjectionConfig() {
- @Override
- public void initMap() {
- // to do nothing
- }
- };
-
- // 如果模板引擎是 freemarker
- String templatePath = "/templates/mapper.xml.ftl";
- // 自定义输出配置
- List<FileOutConfig> focList = new ArrayList<>();
- // 自定义配置会被优先输出
- focList.add(new FileOutConfig(templatePath) {
- @Override
- public String outputFile(TableInfo tableInfo) {
- // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
- if (StringUtils.isNotBlank(pc.getModuleName())) {
- return projectPath + "/src/main/resources/mappers/" + pc.getModuleName() + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
- } else {
- return projectPath + "/src/main/resources/mappers/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
- }
- }
- });
- cfg.setFileOutConfigList(focList);
- mpg.setCfg(cfg);
- // 配置模板
- TemplateConfig templateConfig = new TemplateConfig();
- templateConfig.setXml(null);
- mpg.setTemplate(templateConfig);
-
- // 5.策略配置
- StrategyConfig strategy = new StrategyConfig();
- // 表名生成策略(下划线转驼峰命名)
- strategy.setNaming(NamingStrategy.underline_to_camel);
- // 列名生成策略(下划线转驼峰命名)
- strategy.setColumnNaming(NamingStrategy.underline_to_camel);
- // 是否启动Lombok配置
- strategy.setEntityLombokModel(true);
- // 是否启动REST风格配置
- strategy.setRestControllerStyle(true);
- // 自定义实体父类strategy.setSuperEntityClass("com.baomidou.mybatisplus.extension.activerecord.Model");
- // 自定义service父接口strategy.setSuperServiceClass("com.baomidou.mybatisplus.extension.service.IService");
- // 自定义service实现类strategy.setSuperServiceImplClass("com.baomidou.mybatisplus.extension.service.impl.ServiceImpl");
- // 自定义mapper接口strategy.setSuperMapperClass("com.baomidou.mybatisplus.core.mapper.BaseMapper");
- strategy.setSuperEntityColumns("id");
-
- // 写于父类中的公共字段plus
- strategy.setSuperEntityColumns("id");
- strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
- strategy.setControllerMappingHyphenStyle(true);
-
- //表名前缀(可变参数):“t_”或”“t_模块名”,例如:t_user或t_sys_user
- strategy.setTablePrefix("t_", "t_sys_");
- //strategy.setTablePrefix(scanner("请输入表前缀"));
- mpg.setStrategy(strategy);
- mpg.setTemplateEngine(new FreemarkerTemplateEngine());
- // 执行
- mpg.execute();
- }
- }
首先你要给那个项目中的java文件夹下面的那个包去生成,你要改这代码生成的指定地方,改动的地方我会标记颜色。
①目前我们的项目是springbootmp 这是代码生成的根路径,这就是配置地址
②作者
③数据库的地址、密码和用户名换成自己的
④指的是我目前项目的启动类所在的位置,就是SpringbootmpApplication它的上一方目录
改好这四个地方就不需要动它了。
MPGenerator.java
package com.jwj.springbootmp.mp;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/**
* mybatis-plus代码生成
*/
public class MPGenerator {
/**
*
* 读取控制台内容
*
*/
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.isNotBlank(ipt)) {
if ("quit".equals(ipt)) return "";
return ipt;
}
}
throw new MybatisPlusException("请输入正确的" + tip + "!");
}
public static void main(String[] args) {
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
// 1.全局配置
GlobalConfig gc = new GlobalConfig();
// System.getProperty("user.dir") 指的是工作区间,就是它test02
String projectPath = System.getProperty("user.dir") + "/springbootmp";
System.out.println(projectPath);
gc.setOutputDir(projectPath + "/src/main/java");
gc.setOpen(false);
gc.setBaseResultMap(true);//生成BaseResultMap
gc.setActiveRecord(false);// 不需要ActiveRecord特性的请改为false
gc.setEnableCache(false);// XML 二级缓存
gc.setBaseResultMap(true);// XML ResultMap
gc.setBaseColumnList(true);// XML columList
//gc.setSwagger2(true); //实体属性 Swagger2 注解
gc.setAuthor("jwj");
// 自定义文件命名,注意 %s 会自动填充表实体属性!
gc.setMapperName("%sMapper");
gc.setXmlName("%sMapper");
gc.setServiceName("%sService");
gc.setServiceImplName("%sServiceImpl");
gc.setControllerName("%sController");
gc.setIdType(IdType.AUTO);
mpg.setGlobalConfig(gc);
// 2.数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setDbType(DbType.MYSQL);
dsc.setUrl("jdbc:mysql://localhost:3306/mybatis_ssm?useUnicode=true&characterEncoding=UTF-8");
dsc.setDriverName("com.mysql.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("123456");
mpg.setDataSource(dsc);
// 3.包配置
PackageConfig pc = new PackageConfig();
String moduleName = scanner("模块名(quit退出,表示没有模块名)");
if (StringUtils.isNotBlank(moduleName)) {
pc.setModuleName(moduleName);
}
// 设置父包
pc.setParent("com.zking.springbootmp")
.setMapper("mapper")
.setService("service")
.setController("controller")
.setEntity("model");
mpg.setPackageInfo(pc);
// 4.自定义配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// to do nothing
}
};
// 如果模板引擎是 freemarker
String templatePath = "/templates/mapper.xml.ftl";
// 自定义输出配置
List focList = new ArrayList<>();
// 自定义配置会被优先输出
focList.add(new FileOutConfig(templatePath) {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
if (StringUtils.isNotBlank(pc.getModuleName())) {
return projectPath + "/src/main/resources/mappers/" + pc.getModuleName() + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
} else {
return projectPath + "/src/main/resources/mappers/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
}
}
});
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
// 配置模板
TemplateConfig templateConfig = new TemplateConfig();
templateConfig.setXml(null);
mpg.setTemplate(templateConfig);
// 5.策略配置
StrategyConfig strategy = new StrategyConfig();
// 表名生成策略(下划线转驼峰命名)
strategy.setNaming(NamingStrategy.underline_to_camel);
// 列名生成策略(下划线转驼峰命名)
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
// 是否启动Lombok配置
strategy.setEntityLombokModel(true);
// 是否启动REST风格配置
strategy.setRestControllerStyle(true);
// 自定义实体父类strategy.setSuperEntityClass("com.baomidou.mybatisplus.extension.activerecord.Model");
// 自定义service父接口strategy.setSuperServiceClass("com.baomidou.mybatisplus.extension.service.IService");
// 自定义service实现类strategy.setSuperServiceImplClass("com.baomidou.mybatisplus.extension.service.impl.ServiceImpl");
// 自定义mapper接口strategy.setSuperMapperClass("com.baomidou.mybatisplus.core.mapper.BaseMapper");
strategy.setSuperEntityColumns("id");
// 写于父类中的公共字段plus
strategy.setSuperEntityColumns("id");
strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
strategy.setControllerMappingHyphenStyle(true);
//表名前缀(可变参数):“t_”或”“t_模块名”,例如:t_user或t_sys_user
strategy.setTablePrefix("t_", "t_sys_");
//strategy.setTablePrefix(scanner("请输入表前缀"));
mpg.setStrategy(strategy);
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
// 执行
mpg.execute();
}
}

在运行这MPGenerator.java里面的main方法的时候改一mysql的版本,不然会报错。

运行结果如图所示:创建成功了


生成出来的代码如下:
MvcBookMapper.xml
- "1.0" encoding="UTF-8"?>
- mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
- <mapper namespace="com.zking.springbootmp.book.mapper.MvcBookMapper">
-
-
- <resultMap id="BaseResultMap" type="com.zking.springbootmp.book.model.MvcBook">
- <id column="bid" property="bid" />
- <result column="bname" property="bname" />
- <result column="price" property="price" />
- resultMap>
-
-
- <sql id="Base_Column_List">
- bid, bname, price
- sql>
-
- mapper>
MvcBookMapper.java
- package com.zking.springbootmp.book.mapper;
-
- import com.zking.springbootmp.book.model.MvcBook;
- import com.baomidou.mybatisplus.core.mapper.BaseMapper;
- import org.springframework.stereotype.Repository;
-
- /**
- *
- * Mapper 接口
- *
- *
- * @author jwj
- * @since 2022-11-04
- */
- @Repository
- public interface MvcBookMapper extends BaseMapper<MvcBook> {
-
- }
MvcBookService.java
- package com.zking.springbootmp.book.service;
-
- import com.zking.springbootmp.book.model.MvcBook;
- import com.baomidou.mybatisplus.extension.service.IService;
-
- /**
- *
- * 服务类
- *
- *
- * @author jwj
- * @since 2022-11-04
- */
- public interface MvcBookService extends IService<MvcBook> {
-
- }
MvcBookServiceImpl.java
- package com.zking.springbootmp.book.service.impl;
-
- import com.zking.springbootmp.book.model.MvcBook;
- import com.zking.springbootmp.book.mapper.MvcBookMapper;
- import com.zking.springbootmp.book.service.MvcBookService;
- import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
- import org.springframework.stereotype.Service;
-
- /**
- *
- * 服务实现类
- *
- *
- * @author jwj
- * @since 2022-11-04
- */
- @Service
- public class MvcBookServiceImpl extends ServiceImpl
, MvcBook> implements MvcBookService { -
- }
简单完善一下基本的增删改查方法测试一下: MvcBookController.java开发
- package com.zking.springbootmp.book.controller;
-
-
- import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
- import com.zking.springbootmp.book.model.MvcBook;
- import com.zking.springbootmp.book.service.MvcBookService;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.web.bind.annotation.*;
-
- import java.util.List;
-
- /**
- *
- * 前端控制器
- *
- *
- * @author jwj
- * @since 2022-11-04
- */
- @RestController
- @RequestMapping("/mp")
- public class MvcBookController {
- @Autowired
- private MvcBookService bookService;
-
- // 查询所有
- @GetMapping("/list")
- public List
list(){ - return bookService.list();
- }
-
- // 按条件查询
- @GetMapping("/listByCondition")
- public List
listByCondition(MvcBook book){ - // 如果使用的是Mybatis,那么我们需要写SQL语句,而mp不需要
- // select * from t_mvc_book where bname like '%2%'; BookMapper.xml
- QueryWrapper qw = new QueryWrapper();
- qw.like("bname",book.getBname());
- return bookService.list();
- }
-
- // 查询单个
- @GetMapping("/get")
- public MvcBook get(MvcBook book) {
- return bookService.getById(book.getBid());
- }
-
- // 增加
- @PutMapping("/add")
- public boolean add(MvcBook book){
- return bookService.save(book);
- }
-
- // 删除
- @DeleteMapping("/del")
- public boolean delete(MvcBook book){
- return bookService.removeById(book.getBid());
- }
-
- // 修改
- @PostMapping("/update")
- public boolean update(MvcBook book){
- return bookService.saveOrUpdate(book);
- }
-
- }
同样的也要进行扫描,扫描写好了然后在这里的mian方法里面运行
SpringbootmpApplication.java
- package com.jwj.springbootmp;
-
- import org.mybatis.spring.annotation.MapperScan;
- import org.springframework.boot.SpringApplication;
- import org.springframework.boot.autoconfigure.SpringBootApplication;
- import org.springframework.transaction.annotation.EnableTransactionManagement;
-
- @MapperScan({"com.zking.springbootmp.book.mapper"})
- @EnableTransactionManagement
- @SpringBootApplication
- public class SpringbootmpApplication {
-
- public static void main(String[] args) {
- SpringApplication.run(SpringbootmpApplication.class, args);
- }
-
- }
这样就是说明运行成功了如图所示:

打开我们的测试工具Eolink

mybatis-plus中依然可以兼容使用Mybatis的相关功能,测试代码如下:
在MvcBookMapper.xml中写入代码如下:
在MvcBookService.java中加入代码如下:
List
在MvcBookServiceImpl.java中加入代码如下:
@Autowired private MvcBookMapper bookMapper; @Override public List
在MvcBookController.java中加入代码如下:测试
// 多表联查,用户账户对应角色的功能,论证mybatisplus是一样可以使用mybatis功能
@GetMapping("/querUserRole")
public List

① 创建项目:lombok、web、jdbc、Mybatis、MySQL、driver
② 更改pom中MySQL的版本号,默认采用的是8.0,然后运行查询数据库会报错,所以改为5.1.44
③ applocation.yml 要配置数据源详细信息:
这一部分配置是替代了spring-Mybatis.xml 的数据源相关配置
④ 在application.yml 文件中需要添加Mybatis 相关配置
classpath:mappers/**/*.xml
⑤ 在SpringBoot启动类***Application添加注解 @MapperScan("com.jwj.*.mapper")
⑥ 利用generateConfig.xml进行Mybatis的代码生成
⑦ 测试
① 创建项目:lombok、web、jdbc、Mybatis-plus、MySQL、driver
② 额外添加Mybatis-plus代码生成的pom依赖,有两个
③ 在项目导入Mybatis-plus的代码生成的类
注意事项:1.需要更改代码生成module名
2.需要设置父包的位置
3.要预先创建好mappers的文件夹
④Mybatis-plus接口
1.basemapper/baseservice 都已经封装了基本的增删改查及基本使用
2.QueryWrapper的使用,可以构建查询条件,减少配置文件xml的sql编写
⑤Mybatis-plus对于Mybatis的兼容
用户、角色、用户角色中间表连表查询的案例