开始了喂~
别眨眼 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();
}
}
搞定啦!是不是很简单?请各位老板,加个关注,点个赞呗!
以后天天来,把开发中的好源码,都分享出来~
更多推荐
MyBatisPlus 最新版代码生成器(直接拿来就能用,包含自动生成 Vue 模版)
发布评论