【web】Springboot3 + Mysql 使用 Mubatis-Plus 代码生成器(新)

发布时间:2024年01月06日

1. 创建项目

java 17

使用 Initializer 创建

2. 用于测试的数据库

  • 创建数据库 test

    create database test;
    show databases;
    use test;
    
  • 创建表

    DROP TABLE IF EXISTS `user`;
    
    CREATE TABLE `user`
    (
        id BIGINT NOT NULL COMMENT '主键ID',
        name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',
        age INT NULL DEFAULT NULL COMMENT '年龄',
        email VARCHAR(50) NULL DEFAULT NULL COMMENT '邮箱',
        PRIMARY KEY (id)
    );
    
  • 插入数据

    DELETE FROM `user`;
    
    INSERT INTO `user` (id, name, age, email) VALUES
    (1, 'Jone', 18, 'test1@baomidou.com'),
    (2, 'Jack', 20, 'test2@baomidou.com'),
    (3, 'Tom', 28, 'test3@baomidou.com'),
    (4, 'Sandy', 21, 'test4@baomidou.com'),
    (5, 'Billie', 24, 'test5@baomidou.com');
    

3. Maven 依赖

Mysql

<!--Mysql-->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.26</version>
</dependency>

MP

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-spring-boot3-starter</artifactId>
    <version>3.5.5</version>
</dependency>

MP 生成器

  • swagger 是可选的,如果不添加该依赖,需要在生成器的代码中注释掉 enableSwagger()
  • lombok 也是可选的,如果不添加该依赖,需要在生成器的代码中注释掉 enableLombok()
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-generator</artifactId>
    <version>3.5.5</version>
</dependency>

<dependency>
    <groupId>io.swagger</groupId>
    <artifactId>swagger-annotations</artifactId>
    <version>1.6.12</version>
</dependency>

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
</dependency>

<!--生成模板-->
<dependency>
    <groupId>org.freemarker</groupId>
    <artifactId>freemarker</artifactId>
    <version>2.3.32</version>
</dependency>

我的 pom.xml

<?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.2.1</version>
        <relativePath/>
    </parent>

    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</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>

        <!--Mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.26</version>
        </dependency>

        <!--MP-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-spring-boot3-starter</artifactId>
            <version>3.5.5</version>
        </dependency>

        <!--MP测试-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter-test</artifactId>
            <version>3.5.5</version>
        </dependency>

        <!--MP生成器-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.5.5</version>
        </dependency>

        <dependency>
            <groupId>io.swagger</groupId>
            <artifactId>swagger-annotations</artifactId>
            <version>1.6.12</version>
        </dependency>

        <!--生成模板-->
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.32</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

4. 生成器

创建生成器类

  • 随便创建一个 Java 类,用于执行生成器代码
  • 我的生成器类是:com/example/demo/CodeGen.java

生成器配置

package com.example.demo;


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 java.io.File;
import java.sql.Types;
import java.util.Collections;

public class CodeGen {
    public static void main(String[] args) {
        // 数据库配置信息
        String url = "jdbc:mysql://localhost:3306/test?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8";
        String username = "root";
        String password = "root";

        // 当前项目路径
        String currentPath = new File("").getAbsolutePath();
        String codeOutputDir = currentPath + "/src/main/java";

        // mapperXml 生成路径
        String mapperXmlPath = currentPath + "/src/main/resources/mapper";

        FastAutoGenerator.create(url, username, password)
                .globalConfig(builder -> {
                    // 设置作者
                    builder.author("demo")
                            // 开启 swagger 模式
                            .enableSwagger()
                            // 指定输出目录
                            .outputDir(codeOutputDir);
                })
                .dataSourceConfig(builder -> builder.typeConvertHandler((globalConfig, typeRegistry, metaInfo) -> {
                    int typeCode = metaInfo.getJdbcType().TYPE_CODE;
                    if (typeCode == Types.SMALLINT) {
                        return DbColumnType.INTEGER;
                    }
                    return typeRegistry.getColumnType(metaInfo);
                }))
                .packageConfig(builder -> {
                    // 设置父包名
                    builder.parent("com.example")
                            // 设置父包模块名
                            .moduleName("demo")
                            // pojo 实体类包名
                            .entity("entity")
                            // Service 包名
                            .service("service")
                            // ***ServiceImpl 包名
                            .serviceImpl("service.impl")
                            // Mapper 包名
                            .mapper("mapper")
                            // Mapper XML 包名
                            .xml("mapper.xml")
                            // Controller 包名
                            .controller("controller")
                            // 设置 mapperXml 生成路径
                            .pathInfo(Collections.singletonMap(OutputFile.xml, mapperXmlPath));
                })
                .strategyConfig(builder -> {
                    // 设置需要生成的表名
                    builder.addInclude("user")
                            // 设置过滤表前缀
                            .addTablePrefix("t_")


                            // Entity 配置
                            .entityBuilder()
                            // 开启 lombok 模型
                            .enableLombok()
                            // 覆盖已生成文件
                            .enableFileOverride()


                            // Controller 配置
                            .controllerBuilder()
                            // 开启生成 @RestController 控制器
                            .enableRestStyle()
                            // 覆盖已生成文件
                            .enableFileOverride()


                            // Service 配置
                            .serviceBuilder()
                            // 覆盖已生成文件
                            .enableFileOverride()


                            // Mapper 配置
                            .mapperBuilder()
                            // 覆盖已生成文件
                            .enableFileOverride();
                })
                // 默认的是 Velocity引擎模板
                .templateEngine(new FreemarkerTemplateEngine())
                .execute();
    }
}

添加 MapperScan

  • 目录结构
    在这里插入图片描述

  • 启动类添加 @MapperScan("com.example.demo.mapper")

    @SpringBootApplication
    @MapperScan("com.example.demo.mapper")
    public class DemoApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(DemoApplication.class, args);
        }
    }
    

application.yml 配置 Mysql 数据源

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/test
    username: root
    password: root

6. 测试

测试类

  • 创建 src/test/java/com/example/demo/MpTest.java
  • 测试代码
    package com.example.demo;
    
    import com.example.demo.entity.User;
    import com.example.demo.mapper.UserMapper;
    import org.junit.jupiter.api.Test;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    
    import java.util.List;
    
    
    @SpringBootTest
    public class MpTest {
        @Autowired
        private UserMapper userMapper;
    
        @Test
        void queryTest() {
            List<User> result = userMapper.selectList(null);
            System.out.println(result);
        }
    }
    
  • 输出
    [User{id = 1, name = Jone, age = 18, email = test1@baomidou.com}, User{id = 2, name = Jack, age = 20, email = test2@baomidou.com}, User{id = 3, name = Tom, age = 28, email = test3@baomidou.com}, User{id = 4, name = Sandy, age = 21, email = test4@baomidou.com}, User{id = 5, name = Billie, age = 24, email = test5@baomidou.com}]
    
文章来源:https://blog.csdn.net/m0_52733659/article/details/135424798
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。