mybatis plus已经支持springboot3.x了,官方目前最新版的是3.5.3,最新版的配置更简单了一些,闲话不说,直接开干。
1.创建Springboot项目,这个就不说了,POM如下
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.1.0</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.afgoals</groupId>
<artifactId>demo4</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo4</name>
<description>demo4</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2、增加mybatis plus、生成器和mysql驱动依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.3</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>3.5.3</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.29</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.3.0</version>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.3</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
3.创建数据库表,这个也不说了吧
4.利用mybatis plus提供的生成器,生成mapper和xml,代码如下
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import java.io.File;
/*
* 代码生成器
*
* @author terrfly
* @site https://www.jeepay.vip
* @date 2021/6/8 17:47
*/
public class MainGen {
public static final String THIS_MODULE_NAME = "demo4"; //当前项目名称
public static final String DB_URL = "jdbc:mysql://192.168.136.5:3306/demo?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8";
public static final String DB_USERNAME = "root";
public static final String DB_PASSWORD = "root";
// 多个用, 拼接
//public static final String TABLE_NAMES= "t_sys_entitlement,t_sys_role,t_sys_user,t_sys_user_auth";
public static final String TABLE_NAMES= "t_dept,t_emp";
public static void main(String[] args) {
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir"); //获取当前项目的 文件夹地址
if(!projectPath.endsWith(THIS_MODULE_NAME)){ //解决IDEA中 项目目录问题
projectPath += File.separator + THIS_MODULE_NAME;
}
gc.setOutputDir(projectPath + "/src/main/java");
gc.setAuthor("[mybatis plus generator]");
gc.setOpen(false);
gc.setBaseResultMap(true);
gc.setDateType(DateType.ONLY_DATE);
gc.setServiceImplName("%sService"); //不生成 service接口;
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl(DB_URL);
dsc.setDriverName("com.mysql.jdbc.Driver");
dsc.setUsername(DB_USERNAME);
dsc.setPassword(DB_PASSWORD);
dsc.setTypeConvert(new MySqlTypeConvert() {
@Override
public DbColumnType processTypeConvert(GlobalConfig globalConfig, String fieldType) {
System.out.println("转换类型:" + fieldType);
//tinyint转换成Boolean
if (fieldType.toLowerCase().contains("tinyint")) {
return DbColumnType.BYTE;
}
return (DbColumnType) super.processTypeConvert(globalConfig, fieldType);
}
});
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setParent("com.afgoals.demo4"); //根目录
pc.setEntity("core.entity"); //实体目录
pc.setMapper("service.mapper"); //Mapper接口目录
pc.setXml("service.mapper"); //xml目录
pc.setService("delete_delete"); //service目录 不需要,暂时删除
pc.setServiceImpl("service"); //serviceImpl 目录
mpg.setPackageInfo(pc);
// 配置模板
TemplateConfig templateConfig = new TemplateConfig();
templateConfig.setController(null); //不生成controller
templateConfig.setService(null); //不生成services
mpg.setTemplate(templateConfig);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel); //no_change原样输出
strategy.setColumnNaming(NamingStrategy.underline_to_camel); //no_change原样输出
strategy.setEntityLombokModel(true);
strategy.setInclude(TABLE_NAMES.split(","));
strategy.setTablePrefix("t_");
// strategy.setEntityTableFieldAnnotationEnable(true); //自动添加 field注解
mpg.setStrategy(strategy);
mpg.execute();
}
}
执行完上面代码,项目结构如下,红框标注的均为自动生成
5.在启动类上增加配置,如下
package com.afgoals.demo4;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
@MapperScan("com.afgoals.demo4.**.mapper") //Mybatis mapper接口路径
public class Demo4Application {
public static void main(String[] args) {
SpringApplication.run(Demo4Application.class, args);
}
}
6.配置yml数据库
spring:
datasource:
url: jdbc:mysql://192.168.136.5:3306/demo?zeroDateTimeBehavior=convertToNull&useUnicode=true&characterEncoding=utf-8&autoReconnect=true&useSSL=false&allowPublicKeyRetrieval=true
username: root
password: root
最后启动项目就可以了,如下代表成功了
最后总结一些问题
1、报错出现org.springframework.core.NestedIOException,如下
如果你遇到这个错了,那说明你是缺少了如下依赖,这个很关键
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>3.5.3</version>
</dependency>
2、报错出现 Invalid bound statement (not found):
出现这种情况 那肯定是用自定义的sql,但是没有映射到xml文件,一般是两种情况
(1)xml文件和mapper接口放在同一个包下面,就像我上面的目录结构一样,
不需要再yml配置文件里额外配置mapper-locations,亲测是这样。
但是需要在pom文件里增加如下配置:
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/resources</directory>
</resource>
<resource>
<directory>src/main/java</directory>
<includes><include>**/*.xml</include></includes><!-- maven可以将mapper.xml进行打包处理,否则仅对java文件处理 -->
</resource>
</resources>
</build>
(2)xml文件既没有和mapper接口放在一个包下,又没有放在resources/mapper 目录下面
那就需要在配置文件里配置 mapper-locations,如下