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版本及其以上的代码生成器工具类相似的内容: