MyBatisPlus代码生成器
Springboot整合MybatisPlus
1.创建一个SpringBoot项目
2.导入相关依赖
<?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>2.2.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.qbb</groupId>
<artifactId>simple-rights-management</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>simple-rights-management</name>
<description>simple-rights-management</description>
<properties>
<java.version>1.8</java.version>
<mybatis-plus.version>3.4.1</mybatis-plus.version>
<freemark.version>2.3.30</freemark.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- mybatis-plus-boot-starter -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>${mybatis-plus.version}</version>
</dependency>
<!-- mybatis-plus-generator MybatisPlus代码生成器需要使用的依赖,仅仅是测试的时候需要使用,后期不需要打入jar宝中 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>${mybatis-plus.version}</version>
<scope>test</scope>
</dependency>
<!--MybatisPlus代码生成器需要使用的模板依赖,仅仅是测试的时候需要使用,后期不需要打入jar宝中-->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>${freemark.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
3.编写代码生成器测试类(参考官方文档:MyBatisPlus)
package com.qbb.simplerightsmanagement;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.builder.ConfigBuilder;
import com.baomidou.mybatisplus.generator.config.po.TableFill;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.FileType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/**
* @author QiuQiu&LL (个人博客:https://www.cnblogs.com/qbbit)
* @version 1.0
* @date 2022-02-23 20:04
* @Description:
*/
public class CodeGenerator {
/**com/qbb/simplerightsmanagement
* <p>
* 读取控制台内容
* </p>
*/
public static String scanner(String tip) {
Scanner scanner = new Scanner(System.in);
StringBuilder help = new StringBuilder();
help.append("请输入" + tip + ":");
System.out.println(help.toString());
if (scanner.hasNext()) {
String ipt = scanner.next();
if (StringUtils.isNotBlank(ipt)) {
return ipt;
}
}
throw new MybatisPlusException("请输入正确的" + tip + "!");
}
public static void main(String[] args) {
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
// 项目根路径
String projectPath = System.getProperty("user.dir");
// 代码生成到哪个目录下
gc.setOutputDir(projectPath + "/src/main/java");
// 作者
gc.setAuthor("QIUQIU&LL");
// 代码生成完毕是否打开文件夹
gc.setOpen(false);
// 设置不以I...Service开头
gc.setServiceName("%Service");
// gc.setDateType(DateType.TIME_PACK) 设置时间格式为Java8
// gc.setSwagger2(true); 实体属性 Swagger2 注解
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://localhost:3306/mybatisplus?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=GMT%2B8");
// dsc.setSchemaName("public");
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("root");
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setModuleName(scanner("模块名"));
pc.setParent("com.qbb");
mpg.setPackageInfo(pc);
// 自定义配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// to do nothing
}
};
// 如果模板引擎是 freemarker
String templatePath = "/templates/mapper.xml.ftl";
// 如果模板引擎是 velocity
// String templatePath = "/templates/mapper.xml.vm";
// 自定义输出配置
List<FileOutConfig> focList = new ArrayList<>();
// 自定义配置会被优先输出
focList.add(new FileOutConfig(templatePath) {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
return projectPath + "/src/main/resources/mapper/" + pc.getModuleName()
+ "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
}
});
cfg.setFileCreate(new IFileCreate() {
@Override
public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
/* // 判断自定义文件夹是否需要创建
checkDir("调用默认方法创建的目录,自定义目录用");
if (fileType == FileType.MAPPER) {
// 已经生成 mapper 文件判断存在,不想重新生成返回 false
return !new File(filePath).exists();
}*/
// 允许生成模板文件,无论之前代码生成器是否生成过,都重新生成
return true;
}
});
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
// 配置模板
TemplateConfig templateConfig = new TemplateConfig();
// 配置自定义输出模板
//指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
// templateConfig.setEntity("templates/entity2.java");
// templateConfig.setService();
// templateConfig.setController();
templateConfig.setXml(null);
mpg.setTemplate(templateConfig);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
// 表名是下划线的转驼峰
strategy.setNaming(NamingStrategy.underline_to_camel);
// 数据库字段转驼峰
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
// 判断是否需要继承父类,从而抽取公共字段
if(scanner("是否需要继承基类?").equalsIgnoreCase("y")){
// 设置父类,解决公共字段冗余
strategy.setSuperEntityClass("com.qbb.simplerightsmanagement.entity.BaseEntity");
// 写于父类中的公共字段
strategy.setSuperEntityColumns("create_time","modified_time","create_account_id","modified_account_id","deleted");
}
// 实体类是否使用lombok
strategy.setEntityLombokModel(true);
// 是否设置Controller为RESTFul风格
strategy.setRestControllerStyle(false);
// 公共父类
// strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!");
strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
// 设置逻辑删除字段
strategy.setLogicDeleteFieldName("deleted");
// 设置自动生成字段策略
ArrayList<TableFill> tableFills = new ArrayList<>();
TableFill createTime = new TableFill("create_time", FieldFill.INSERT);
TableFill modifiedTime = new TableFill("modified_time", FieldFill.UPDATE);
TableFill createAccountId = new TableFill("create_account_id", FieldFill.INSERT);
TableFill modifiedAccountId = new TableFill("modified_account_id", FieldFill.UPDATE);
tableFills.add(createTime);
tableFills.add(modifiedTime);
tableFills.add(createAccountId);
tableFills.add(modifiedAccountId);
strategy.setTableFillList(tableFills);
// Controller的RequestMapping路径是否驼峰
strategy.setControllerMappingHyphenStyle(true);
// 表名前缀
// strategy.setTablePrefix(pc.getModuleName() + "_");
mpg.setStrategy(strategy);
// 使用什么模板引擎
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
}
}
基类信息
package com.qbb.simplerightsmanagement.entity;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableLogic;
import lombok.Data;
import java.time.LocalDateTime;
/**
* @author QiuQiu&LL (个人博客:https://www.cnblogs.com/qbbit)
* @version 1.0
* @date 2022-02-23 20:29
* @Description:
*/
@Data
public class BaseEntity {
/**
* 创建时间
*/
@TableField(fill = FieldFill.INSERT)
private LocalDateTime createTime;
/**
* 修改时间
*/
@TableField(fill = FieldFill.UPDATE)
private LocalDateTime modifiedTime;
/**
* 创建人
*/
@TableField(fill = FieldFill.INSERT)
private Long createAccountId;
/**
* 修改人
*/
@TableField(fill = FieldFill.UPDATE)
private Long modifiedAccountId;
/**
* 逻辑删除标识(0、否 1、是)
*/
@TableLogic
private Integer deleted;
}
数据库信息
分类:
7、MybatisPlus
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构