本案例版本
springboot 3.1.12
mybatis-plus 3.5.9
源码地址
stormlong/springboot-mybatisplus
集成 mybatis-plus
官方文档:快速开始 | MyBatis-Plus
引入依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-spring-boot3-starter</artifactId>
<version>3.5.9</version>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
yml配置
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: 123456
url: jdbc:mysql://127.0.0.1:3306/springboot-oauth2?useSSL=false&characterEncoding=utf8&serverTimezone=Asia/Shanghai&remarks=true&useInformationSchema=true&tinyInt1isBit=true
mybatis-plus:
# 指定 MyBatis Mapper 对应的 XML 文件位置
mapper-locations: classpath:/mapper/**.xml
configuration:
# 开启自动驼峰命名规则(camel case)映射
map-underscore-to-camel-case: true
如果使用 代码生成器,在连接上添加链接属性
启动类中修改
在 Spring Boot 启动类中添加 @MapperScan
注解,扫描 Mapper 文件夹
路径根据自己项目的 mapper 文件路径填写
@MapperScan("com.baomidou.mybatisplus.samples.quickstart.mapper")
集成代码生成器
引入依赖
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- MyBatis-Plus 从 3.0.3 之后移除了代码生成器与模板引擎的默认依赖,
需要手动添加相关依赖-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.5.9</version>
</dependency>
<!-- 添加 模板引擎 依赖-->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.34</version>
</dependency>
代码生成主类
strategyConfig 配置中显式配置了文件可覆盖生成,不配置则文件不覆盖
package com.mybatis.plus.demo.generator;
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import org.apache.ibatis.type.JdbcType;
import java.nio.file.Paths;
import java.util.Collections;
/**
* @author thl
* @date 2025/1/10
* @description
**/
public class CodeGenerator {
private static final String url = "jdbc:mysql://127.0.0.1:3306/springboot-oauth2?useSSL=false&characterEncoding=utf8&serverTimezone=Asia/Shanghai&remarks=true&useInformationSchema=true&tinyInt1isBit=true";
private static final String username = "root";
private static final String password = "123456";
public static void main(String[] args) {
FastAutoGenerator.create(url, username, password)
.globalConfig(builder -> {
builder.author("thl") // 设置作者
.outputDir(Paths.get(System.getProperty("user.dir")) + "/src/main/java") // 指定输出目录
.commentDate("yyyy-MM-dd HH:mm:ss").disableOpenDir()
;
})
.dataSourceConfig(builder ->
builder.typeConvertHandler((globalConfig, typeRegistry, metaInfo) -> {
// 兼容旧版本转换成Integer
if (JdbcType.TINYINT == metaInfo.getJdbcType()) {
return DbColumnType.INTEGER;
}
return typeRegistry.getColumnType(metaInfo);
})
)
.packageConfig(builder ->
builder.parent("com.mybatis.plus.demo") // 设置父包名
.entity("model")
.mapper("mapper")
.service("service")
.serviceImpl("service.impl")
.controller("controller")
.xml("mapper.xml")
.pathInfo(Collections.singletonMap(OutputFile.xml,
Paths.get(System.getProperty("user.dir")) + "/src/main/resources/mapper")) // 设置mapperXml生成路径
)
.strategyConfig(builder ->
// 设置需要生成的表名
builder.addInclude("oauth2_user")
.controllerBuilder().enableFileOverride().enableRestStyle()
.serviceBuilder().enableFileOverride()
.mapperBuilder().enableFileOverride()
.entityBuilder().enableFileOverride()
)
.templateEngine(new FreemarkerTemplateEngine()) // 默认的是Velocity引擎模板
.execute();
}
}
打印sql
yml 配置
mapper 路径根据自己项目设置
logging:
level:
# 开启sql日志,去除 sql 语句查询结果
com.mybatis.plus.demo.mapper: debug
数据库新建表
DROP TABLE IF EXISTS `oauth2_user`;
CREATE TABLE `oauth2_user` (
`id` bigint(20) NOT NULL COMMENT '主键ID',
`username` varchar(30) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '姓名',
`age` int(11) NULL DEFAULT NULL COMMENT '年龄',
`ou_password` varchar(60) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '密码',
`email` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '邮箱',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;
项目目录结构
使用
生成代码
运行 代码生成器主类 CodeGenerator, 自动生成 controller、service、service.impl、mapper、model、mapper.xml 文件
测试类
package com.mybatis.plus.demo;
import com.mybatis.plus.demo.mapper.Oauth2UserMapper;
import com.mybatis.plus.demo.model.Oauth2User;
import jakarta.annotation.Resource;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
@SpringBootTest
class MybatisPlusAppTests {
@Resource
private Oauth2UserMapper oauth2UserMapper;
@Test
void testInsert() {
Oauth2User oauth2User = new Oauth2User();
oauth2User.setId(123236l);
oauth2User.setUsername("user");
oauth2User.setAge(18);
oauth2User.setOuPassword("password");
oauth2UserMapper.insert(oauth2User);
assertThat(oauth2User.getId()).isNotNull();
}
@Test
void testSelect() {
List<Oauth2User> userlist = oauth2UserMapper.findUserByUserName("user");
userlist.forEach(user-> System.out.println(user.toString()));
}
}