開始了喂~
别眨眼 O,O
一、編輯 pom.xml 檔案,添加依賴
注意:
- 資料庫,我用的是 PostgreSQL,用 MySQL 的同學記得自己換哈~
- 模版,我用的是 FreeMarker,用 Velocity 的同學記得自己換哈~
<properties>
<java.version>18</java.version>
<postgresql.version>42.3.6</postgresql.version>
<druid.version>1.2.10</druid.version>
<mybatis-plus.version>3.5.1</mybatis-plus.version>
<mybatis-plus-generator.version>3.5.2</mybatis-plus-generator.version>
<freemarker.version>2.3.31</freemarker.version>
</properties>
<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>
<!-- 資料庫相關 -->
<!-- postgresql 資料庫連接配接驅動 -->
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>${postgresql.version}</version>
</dependency>
<!-- druid 資料庫連接配接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>${druid.version}</version>
</dependency>
<!-- mybatis-plus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>${mybatis-plus.version}</version>
</dependency>
<!-- mybatis-plus 自動生成代碼子產品 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>${mybatis-plus-generator.version}</version>
</dependency>
<!-- FreeMarker 模闆引擎 -->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>${freemarker.version}</version>
</dependency>
<dependency>
<groupId>org.jetbrains</groupId>
<artifactId>annotations</artifactId>
<version>RELEASE</version>
<scope>compile</scope>
</dependency>
二、編輯 application.properties 檔案
# SpringBoot 啟動端口
server.port=9999
# 資料源
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=org.postgresql.Driver
spring.datasource.username=hello
spring.datasource.password=hello1234
spring.datasource.url=jdbc:postgresql://localhost:5432/auto_trader
# 日志存放位置
logging.file.name=./log/hello.txt
# 日志的等級
# com.hello 是你的包路徑
logging.level.com.hello=debug
#作者
code.generated.author=hello
#//待生成對象表名
code.generated.table-name=你的資料表名,多張表用逗号隔開
三、建立「代碼自動生成器」類:AutoCodeGenerator
我在 src/main/java/ 目錄下,建立了一個 AutoCodeGenerator 檔案。
你看,它要導入巨多的包(不過,這些都是自動導入的,我就是想湊字數,貼出來給你看看)
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.TemplateConfig;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import org.apache.ibatis.jdbc.ScriptRunner;
import org.jetbrains.annotations.NotNull;
import org.springframework.web.bind.annotation.RestController;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.*;
import java.util.function.Consumer;
具體代碼也無敵多,建議:逐字逐句閱讀,盡可能一次性搞懂,加油!
public class AutoCodeGenerator {
private static String driverClassName; // 驅動名稱
private static String username; // 資料庫使用者名
private static String password; // 資料庫使用者密碼
private static String url; // 資料庫連接配接URL
private static String author; // 作者
private static String tableName; // 待生成對象表名
/**
* 讀取 application.properties 配置檔案
*/
private static void readProperty() throws IOException {
Properties properties = new Properties();
// 讀取檔案并轉換編碼為 UTF-8,解決 application.properties 配置檔案中文亂碼
InputStreamReader inputStreamReader = new InputStreamReader(Objects.requireNonNull(AutoCodeGenerator.class.getClassLoader().getResourceAsStream("application.properties")), StandardCharsets.UTF_8);
properties.load(inputStreamReader);
driverClassName = properties.getProperty("spring.datasource.driver-class-name");
username = properties.getProperty("spring.datasource.username");
password = properties.getProperty("spring.datasource.password");
url = properties.getProperty("spring.datasource.url");
author = properties.getProperty("code.generated.author");
tableName = properties.getProperty("code.generated.table-name");
}
/**
* MyBatis-Plus 代碼生成器「新」
* 适用版本:mybatis-plus-generator 3.5.1 及其以上版本,對曆史版本不相容
* 執行 run
*/
public static void main(String[] args) throws Exception {
// 加載資料庫配置
readProperty();
// 項目路徑
String projectPath = System.getProperty("user.dir");
// 根據資料源資訊,建立檔案,生成代碼
FastAutoGenerator.create(new DataSourceConfig.Builder(url,username,password))
// 全局配置
.globalConfig(builder -> builder
// 作者
.author(author)
// 輸出路徑
.outputDir(projectPath + "/target/generated-sources")
.dateType(DateType.TIME_PACK))
// 包配置
.packageConfig(builder -> builder
// 指定父包名
.parent("com.hello")
.entity("entities")
.service("services")
.serviceImpl("services.impl")
.mapper("mapper")
.controller("models"))
// 模版配置
.templateConfig(builder -> builder
.entity("/templates/entity.java")
.service("/templates/service.java")
.serviceImpl("/templates/serviceImpl.java")
.mapper("/templates/mapper.java")
.controller("/templates/controller.java"))
// 政策配置
.strategyConfig(builder -> builder
// 指定表名,用逗号分隔
.addInclude(tableName.split(","))
// 先開啟 Controller 配置
.controllerBuilder()
// 開啟生成 @RestController 控制器
.enableRestStyle()
// 開啟駝峰轉連字元
.enableHyphenStyle()
// 先開啟 Entity 配置
.entityBuilder()
// 開啟主鍵自增
.idType(IdType.AUTO)
// 資料庫表映射到實體的命名政策,駝峰命名
.naming(NamingStrategy.underline_to_camel)
// 資料庫表字段映射到實體的命名政策,駝峰命名
.columnNaming(NamingStrategy.underline_to_camel)
// 開啟生成實體時生成字段注解
.enableTableFieldAnnotation())
// 自定義配置:用來生産前端部分的 Vue 頁面
.injectionConfig(consumer -> {
Map<String, String> customFile = new HashMap<>();
// 根據指定的模版,生成對應的檔案
customFile.put("aaa.vue", "/templates/aaa.vue.ftl");
customFile.put("bbb.vue", "/templates/bbb.vue.ftl");
consumer.customFile(customFile);
})
// freemarker 模版
.templateEngine(new FreemarkerTemplateEngine(){
@Override
protected void outputCustomFile(@NotNull Map<String, String> customFile, @NotNull TableInfo tableInfo, @NotNull Map<String, Object> objectMap) {
//存放取出的實體名稱,用于生成路由
List<String> entityNames = new ArrayList<>();
if (!entityNames.contains(tableInfo.getEntityName())){
entityNames.add(tableInfo.getEntityName());
}
customFile.forEach((key, value) -> {
String fileName = String.format(projectPath + "/src/main/resources/static/" + tableInfo.getEntityName() + File.separator + tableInfo.getEntityName() + "%s", key);
this.outputFile(new File(fileName), objectMap, value, this.getConfigBuilder().getInjectionConfig().isFileOverride());
});
// 生成路由部分
Map<String, Object> routers = new HashMap<>();
routers.put("author", author);
routers.put("date", new Date());
routers.put("entities", entityNames);
// 使用 freemarker 模闆引擎,路由頁面路徑
String templateRoutesPath = "/templates/routes_generated.js.ftl";
// 生成的路由頁面路徑
File templateRoutesOutFile = new File(projectPath + "/src/main/resources/static/routes_generated.js");
try {
this.writer(routers, templateRoutesPath, templateRoutesOutFile);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
})
// 執行
.execute();
}
}