新手使用Mybatis-plus代码生成器
自动生成controller、service、dao、mapper、pojo代码
1 maven依赖导入
我用的是2.3.7的Springboot 3.4.2的mydbtis-plus
这里导入的maven是用来自动生成代码的,自己项目中也需要再重新创建一个新的Module模块,用来存放自动生成的代码
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.2</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.41</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- druid数据源驱动 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
<!-- RESTful APIs swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
<exclusions>
<exclusion>
<groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId>
</exclusion>
<exclusion>
<groupId>io.swagger</groupId>
<artifactId>swagger-models</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId>
<version>1.5.21</version>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-models</artifactId>
<version>1.5.21</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.3.1</version>
</dependency>
<!-- mybatis-plus代码生成器 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.3.1.tmp</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
代码存放的Module中的pom.xml的配置根据自己的需要导入(直接复制上边儿的导入也可以)
2 项目结构图
我的事例中创建的项目框架如下图所示:
[注意]
- 红色的Module(可以把这个模块和绿色模块 都放在同一个父目录下,我是为了测试,就直接又在红色模块中新建了一个新的模块)是用来进行自动代码生成的模块
- 绿色的模块是存放自动生成的代码的模块
3 创建自动代码生成类
我直接新建了一个CodeGenerate文件夹,在里边儿新建了一个CodeGenerate的java类
代码如下:
package com.example.mydbtisplus.CodeGenerate;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
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.po.TableInfo;
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 xiegege
*/
public class CodeGenerator {
// 数据库连接地址
private static final String URL = "jdbc:mysql://localhost:3306/white_jotter?useUnicode=true&characterEncoding=utf8&useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=GMT%2B8";
// 数据库连接驱动
private static final String DRIVER_NAME = "com.mysql.jdbc.Driver";
// 数据库连接用户名
private static final String USERNAME = "root";
// 数据库连接密码
private static final String PASSWORD = "123456";
// 模块名(可选)
private static final String MODULE_NAME = "";
// 项目路径
private static final String PROJECT_PATH = System.getProperty("user.dir");
// xxx.java文件放置路径
private static String JAVA_PATH = "/src/main/java";
// xxxMapper.xml文件放置路径
private static String XML_PATH = "/src/main/resources/mapper/";
private static final String SCANNER_TEXT = "请输入";
/**
* 自动生成代码
*/
public static void main(String[] args) {
scannerModuleName("maven模块名(如:common)");
String parentPackageName = scanner("父包名(如:com.xxx.xxx)");
String author = scanner("开发人员(作者)");
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
// TODO 全局配置
GlobalConfig gc = new GlobalConfig();
// 生成文件的输出目录
gc.setOutputDir(PROJECT_PATH + JAVA_PATH);
// 作者
gc.setAuthor(author);
// 是否打开输出目录
gc.setOpen(false);
// controller 命名方式,注意 %s 会自动填充表实体属性
gc.setControllerName("%sController");
// service 命名方式
gc.setServiceName("%sService");
// serviceImpl 命名方式
gc.setServiceImplName("%sServiceImpl");
// mapper 命名方式
gc.setMapperName("%sMapper");
// xml 命名方式
gc.setXmlName("%sMapper");
// 开启 swagger2 模式
gc.setSwagger2(true);
// 是否覆盖已有文件
gc.setFileOverride(true);
// 是否开启 ActiveRecord 模式
gc.setActiveRecord(true);
// 是否在xml中添加二级缓存配置
gc.setEnableCache(false);
// 是否开启 BaseResultMap
gc.setBaseResultMap(false);
// XML columList
gc.setBaseColumnList(false);
// 全局 相关配置
mpg.setGlobalConfig(gc);
// TODO 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl(URL);
dsc.setDriverName(DRIVER_NAME);
dsc.setUsername(USERNAME);
dsc.setPassword(PASSWORD);
mpg.setDataSource(dsc);
// TODO 包配置
PackageConfig pc = new PackageConfig();
// 父包名。如果为空,将下面子包名必须写全部, 否则就只需写子包名
pc.setParent(parentPackageName);
// 模块名,可以不指定
pc.setModuleName(MODULE_NAME);
// Controller包名
pc.setController("controller");
// Service包名
pc.setService("service");
// ServiceImpl包名
pc.setServiceImpl("service.impl");
// Mapper 包名
pc.setMapper("mapper");
// Entity包名
pc.setEntity("pojo");
mpg.setPackageInfo(pc);
// TODO 自定义配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// to do nothing
}
};
// 输出文件配置
List<FileOutConfig> focList = new ArrayList<>();
focList.add(new FileOutConfig("/templates/mapper.xml.ftl") {
@Override
public String outputFile(TableInfo tableInfo) {
// Mapper.xml 文件存放地址及文件名
return PROJECT_PATH + XML_PATH + MODULE_NAME + "/" + tableInfo.getEntityName() + "Mapper.xml";
}
});
// 自定义输出文件
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
mpg.setTemplate(new TemplateConfig().setXml(null));
// TODO 策略配置
StrategyConfig strategy = new StrategyConfig();
// 数据库表映射到实体的命名策略,驼峰原则
strategy.setNaming(NamingStrategy.underline_to_camel);
// 字数据库表字段映射到实体的命名策略,驼峰原则
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
// 实体是否生成 serialVersionUID
strategy.setEntitySerialVersionUID(false);
// 是否生成实体时,生成字段注解
strategy.setEntityTableFieldAnnotationEnable(true);
// 使用lombok
strategy.setEntityLombokModel(true);
// 设置逻辑删除键
strategy.setLogicDeleteFieldName("del_flag");
// TODO 指定生成的bean的数据库表名
strategy.setInclude(scanner("表名,多个表使用英文逗号分割").split(","));
// 驼峰转连字符
strategy.setControllerMappingHyphenStyle(true);
mpg.setStrategy(strategy);
// 选择 freemarker 引擎需要指定如下加,注意 pom 依赖必须有!
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
}
/**
* 模块名键盘输入
*
* @param text 提示文字
*/
public static void scannerModuleName(String text) {
Scanner scanner = new Scanner(System.in);
System.out.println(SCANNER_TEXT + text);
if (scanner.hasNext()) {
String moduleName = scanner.next();
if (StringUtils.isNotEmpty(moduleName)) {
JAVA_PATH = "/" + moduleName + JAVA_PATH;
XML_PATH = "/" + moduleName + XML_PATH;
return;
}
}
throw new MybatisPlusException(SCANNER_TEXT + "正确的" + text + "!");
}
/**
* 通用键盘输入
*
* @param text 提示文字
*/
public static String scanner(String text) {
Scanner scanner = new Scanner(System.in);
System.out.println(SCANNER_TEXT + text + ":");
if (scanner.hasNext()) {
String str = scanner.next();
if (StringUtils.isNotEmpty(str)) {
return str;
}
}
throw new MybatisPlusException(SCANNER_TEXT + "正确的" + text + "!");
}
}
需要修改的地方就只有数据库链接地址(需要修改成自己的)
4 运行程序
直接运行CodeGenerate的main程序,运行如下图所示:
- maven模块名:刚开始提到的绿色的新建的Module模块(存放代码的模块)
- 父包名:绿色模块中java文件下的父包
- 开发人员名称:看个人,自定义即可
- 表名:输入自己已经新建好的数据库表的名称(注意⚠️,表的名字一定不能出错误,并且多个表的中间用英文!!!!英文!!!英文!!!逗号分隔)
之后就等他自动生成代码即可。
转自原文:https://blog.csdn.net/weixin_42825651/article/details/108747297