Mybatiplus通用3.5.1版本及其以上的代码生成器工具类

mybatiplus,通用,版本,及其,以上,代码,生成器,工具 · 浏览次数 : 90

小编点评

The provided code demonstrates the usage of the `AutoGeneratorTools` class to generate code for an MyBatis Plus 3.5.1 project. Here's a summary of its functionality: **Purpose:** * This code generates the necessary Java code for a MyBatis Plus project, including entity classes, service classes, mapper classes, and controller classes. * It uses a `FastAutoGenerator` to automatically configure and create the project's structure and corresponding files. **Key Features:** * The code is designed to be used within a Java project and assumes the presence of `application.properties` file containing database connection settings. * It provides flexible configuration options through `DataConfigBuilder` and allows customization of entity, service, and mapper mappings. * The generated code follows MyBatis Plus standards, including the use of `FieldFill`, `IdType`, `DateType`, and `TableFills`. * It supports the creation of entity, service, and mapper classes, along with corresponding SQL statements for data access. * The generated code also includes the `mapper.xml` file for mapping between data entities and SQL tables. **Steps Involved:** 1. **Get database configuration:** The code retrieves the database connection URL, username, and password from the `application.properties` file. 2. **Create Data Source Configuration:** An instance of `DataSourceConfig.Builder` is created with the database connection details. 3. **Generate Code:** The `FastAutoGenerator` is initialized with the data source configuration and various settings. 4. **Generate Code:** The `create() ` method is called on the `FastAutoGenerator` to generate the project code. 5. **Output Code:** The generated code is written to the specified output directory within the project. **Output:** The generated code will include the following Java classes: * Entity classes * Service classes * Mapper classes * Controller classes * `mapper.xml` mapping file **Customization:** * The `AutoGeneratorTools` class provides various configuration options through `DataConfigBuilder`. * Users can customize entity, service, and mapper mappings by providing specific configurations. * The `templateEngine` is used to specify the output directory and file naming convention. **Overall, this code provides a convenient and automated way to generate the necessary code for a basic MyBatis Plus project, reducing the need for manual coding and ensuring code quality.**

正文

Mybatiplus通用3.5.1版本及其以上的代码生成器工具类

package com.gton.util;

import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.querys.MySqlQuery;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.engine.VelocityTemplateEngine;
import com.baomidou.mybatisplus.generator.fill.Column;
import com.baomidou.mybatisplus.generator.fill.Property;
import com.baomidou.mybatisplus.generator.keywords.MySqlKeyWordsHandler;

import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Properties;

/**
 * @description: Mybatis-Plus3.5.1代码生成器
 * @author: GuoTong
 * @createTime: 2022-02-13 16:59
 * @since JDK 1.8 OR 11
 **/
@SuppressWarnings("unchecked")
public class AutoGeneratorTools {

    /**
     * Description:
     * 使用前:
     * 指定生成的模块名称:modelName
     * 指定生成业务子包名称:mkdirFiile
     *
     * @author: GuoTong
     * @date: 2022-10-22 22:03:01
     */
    private static String modelName = "/commodity/";
    // 按照业务划分不同多个子包
    private static String mkdirFiile = "user";

    private final String url = "jdbc:mysql://127.0.0.1:3306/study?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC";

    // 高版本的DataSource不需要驱动 保留
    private final String driver = "com.mysql.jdbc.Driver";

    private final String username = "root";
    private final String password = "root";


    public static void main(String[] args) {
        AutoGeneratorTools autoGeneratorTools = new AutoGeneratorTools();
        String userDir = System.getProperty("user.dir");
        String path = "src/main/java";
        String parentPath = "com.gton." + mkdirFiile;
        String mapperXmlPath = "/com/gton/" + mkdirFiile + "/mapper/xml";
        List<String> tables = new ArrayList<>();
        tables.add("product_buying");
        autoGeneratorTools.getDataSourceByFile();
        // 代码自动生成
        autoCreateCode(autoGeneratorTools, userDir, path, parentPath, mapperXmlPath, tables);

    }

    private Properties getDataSourceByFile() {
        FileInputStream dataSource = null;
        InputStream dataSourceStream = null;

        try {
            String property = System.getProperty("user.dir");
            dataSource = new FileInputStream(property + "/common/src/main/resources/application.properties");
            dataSourceStream = new BufferedInputStream(dataSource);
            Properties ps = new Properties();
            ps.load(dataSourceStream);
            return ps;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (dataSourceStream != null) {
                try {
                    dataSourceStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (dataSource != null) {
                try {
                    dataSource.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return new Properties();
    }

    private static void autoCreateCode(AutoGeneratorTools autoGeneratorTools, String userDir, String path, String parentPath, String mapperXmlPath, List<String> tables) {
        FastAutoGenerator.create(autoGeneratorTools.getDataConfigBuilder()).
                globalConfig(builder ->
                        builder.author("GuoTong").
                                commentDate("yyyy-MM-dd").
                                enableSwagger().
                                dateType(DateType.TIME_PACK).
                                disableOpenDir().
                                outputDir(userDir + modelName + path)).
                packageConfig(builder ->
                        builder.parent(parentPath).
                                moduleName("").
                                entity("entity").
                                service("service").
                                serviceImpl("service.impl").
                                mapper("mapper").
                                xml("mapper.xml").
                                controller("controller").
                                pathInfo(Collections.singletonMap(OutputFile.mapperXml, userDir + modelName + path + mapperXmlPath))).
                strategyConfig(builder ->
                        builder.addInclude(tables).
                                entityBuilder().
                                idType(IdType.ASSIGN_ID).
                                enableLombok().
                                enableTableFieldAnnotation().
                                enableChainModel().
                                logicDeleteColumnName("is_del").
                                logicDeletePropertyName("isDel").
                                addTableFills(new Column("create_time", FieldFill.INSERT)).
                                addTableFills(new Property("createTime", FieldFill.INSERT)).
                                addTableFills(new Column("update_time", FieldFill.INSERT_UPDATE)).
                                addTableFills(new Property("updateTime", FieldFill.INSERT_UPDATE)).
                                controllerBuilder().
                                formatFileName("%sController").
                                enableRestStyle().
                                serviceBuilder().
                                formatServiceFileName("%sService").
                                formatServiceImplFileName("%sServiceImpl").
                                mapperBuilder().
                                enableBaseColumnList().
                                enableMapperAnnotation().
                                enableBaseResultMap().
                                formatMapperFileName("%sMapper").
                                formatXmlFileName("%sMapper")).
                templateEngine(new VelocityTemplateEngine()).execute();
    }


    private DataSourceConfig.Builder getDataConfigBuilder() {
        Properties dataSourceByFile = getDataSourceByFile();
        Object dbURl = dataSourceByFile.getOrDefault("spring.datasource.url", url);
        Object dbUsername = dataSourceByFile.getOrDefault("spring.datasource.username", username);
        Object dbPassword = dataSourceByFile.getOrDefault("spring.datasource.password", password);
        return new DataSourceConfig.Builder(dbURl.toString(), dbUsername.toString(), dbPassword.toString()).
                dbQuery(new MySqlQuery()).
                keyWordsHandler(new MySqlKeyWordsHandler()).
                schema("Mybatis-Plus").
                typeConvert(new MySqlTypeConvert());
    }
}

可以读取classpath下的数据源配置:application.properties


#数据源
spring.datasource.url=jdbc:mysql://130.33.238.27:3306/cloud_market?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=root

与Mybatiplus通用3.5.1版本及其以上的代码生成器工具类相似的内容:

Mybatiplus通用3.5.1版本及其以上的代码生成器工具类

Mybatiplus通用3.5.1版本及其以上的代码生成器工具类 package com.gton.util; import com.baomidou.mybatisplus.annotation.FieldFill; import com.baomidou.mybatisplus.annotati

mybatisplus 中查询的实体对应的表名是动态的解决方案

开发中遇到需要查询一些表里的数据,这些数据按照一定的规则存放在不同的数据库表里,例如表名是table_name+月份 table_name_2024_05,table_name_2024_04这样,这些表的结构都相同。 网上找了一些动态修改实体对应数据库表名的方法,操作相对复杂而且跟mybatisp

Springboot+Mybatisplus+ClickHouse集成

# 核心依赖引入 ```xml ru.yandex.clickhouse clickhouse-jdbc 0.1.53 com.baomidou mybatis-plus-boot-starter 3.5.1 org.springframework.boot spring-boot-starter-

基于EasyCode定制Mybatisplus全自动单表实现:新增/批量新增/修改/批量删除/分页查询/ID查询

基于EasyCode定制Mybatisplus全自动单表实现CRUD接口 分页查询 ID查询 新增 批量新增 修改 批量删除 注意使用了MybatisPlus的自动填充功能,和insertBatchSomeColumn扩展批量插入功能,分页插件 需要几个增加插件实现类 自动填充 package co

多租户基于Springboot+MybatisPlus实现使用一个数据库一个表 使用字段进行数据隔离

# 多租户实现方式 ```properties 多租户在数据存储上主要存在三种方案,分别是: 1. 独立数据库 即一个租户一个数据库,这种方案的用户数据隔离级别最高,安全性最好,但成本较高。 优点:为不同的租户提供独立的数据库,有助于简化数据模型的扩展设计,满足不同租户的独特需求;如果出现故障,恢复

SpringBoot彩蛋之定制启动画面

写在前面 在日常开发中,我们经常会看到各种各样的启动画面。例如以下几种 ① spring项目启动画面 ② mybatisplus启动画面 ③若依项目启动画面 还有很多各式各样好看的启动画面,那么怎么定制这些启动画面呢? 一、小试牛刀 ① 新建一个SpringBoot项目 ②在项目的resources

关于对于Java中Entity以及VO,以及DTO中Request对象序列化的学习

关于 Serializable的探讨 前提引入 是由于软件测试上有同学提到说,什么该字段在程序刚运行时,导致jvm激增,所以吸引了我的注意 回顾代码 MybatisPlus Generator自动生成的entity中就经常带有这个, 而且我在开发代码的时候VO,以及DTO常常是直接复制对应的enti

Mybatisplus3.5.1+shardingsphere-jdbc5.1.1分表

> 注意使用雪花ID的话,查询ID时候必须使用long类型的ID,不要使用MP自带的默认的Serializable类型。否则会提示分片主键id数据类型和分片算法不匹配Inline sharding algorithms expression `xxx` and sharding column `xx