推荐链接:
总结——》【Java】
总结——》【Mysql】
总结——》【Spring】
总结——》【SpringBoot】
总结——》【MyBatis、MyBatis-Plus】
/*
Schema:test
Info:测试数据库
Date:2022/09/07 13:49:38
*/
-- 1、创建数据库
CREATE
DATABASE `xiaoxian` CHARACTER SET 'utf8' COLLATE 'utf8_general_ci';
-- 2、创建表
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user`
(
`id` bigint NOT NULL AUTO_INCREMENT,
`name` varchar(10) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
`version` int NOT NULL DEFAULT '0' COMMENT '乐观锁版本号',
`is_delete` tinyint(1) NOT NULL DEFAULT '0' COMMENT '逻辑删除标识1:已删除,0:未删除',
`create_user` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT '创建用户',
`create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
`update_user` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT '更新用户',
PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb3 ROW_FORMAT=DYNAMIC;
-- 3、插入数据
INSERT INTO `xiaoxian`.`user` (`id`, `name`, `version`, `is_delete`, `create_user`, `create_time`, `update_time`,
`update_user`)
VALUES (1, '赵', 0, 0, 'system', '2022-08-16 13:44:57', '2022-08-16 13:45:11', 'system');
INSERT INTO `xiaoxian`.`user` (`id`, `name`, `version`, `is_delete`, `create_user`, `create_time`, `update_time`,
`update_user`)
VALUES (2, '钱', 0, 0, 'system', '2022-08-16 13:44:57', '2022-08-16 13:45:11', 'system');
INSERT INTO `xiaoxian`.`user` (`id`, `name`, `version`, `is_delete`, `create_user`, `create_time`, `update_time`,
`update_user`)
VALUES (3, '孙', 0, 0, 'system', '2022-08-16 13:44:57', '2022-08-16 13:45:11', 'system');
INSERT INTO `xiaoxian`.`user` (`id`, `name`, `version`, `is_delete`, `create_user`, `create_time`, `update_time`,
`update_user`)
VALUES (4, '李', 0, 0, 'system', '2022-08-16 13:44:57', '2022-08-16 13:45:11', 'system');
<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.0modelVersion>
<parent>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-parentartifactId>
<version>2.7.1version>
<relativePath/>
parent>
<groupId>com.xiaoxiangroupId>
<artifactId>mybatisplus-generatorartifactId>
<version>0.0.1-SNAPSHOTversion>
<name>generatorname>
<description>springboot-mybatisplus-generatordescription>
<properties>
<java.version>1.8java.version>
<druid.version>1.1.22druid.version>
<mybatis.plus.version>3.4.1mybatis.plus.version>
<guava.version>28.2-jreguava.version>
<knife4j.version>2.0.8knife4j.version>
<fastjson.version>1.2.70fastjson.version>
properties>
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-jdbcartifactId>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<scope>runtimescope>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druid-spring-boot-starterartifactId>
<version>${druid.version}version>
dependency>
<dependency>
<groupId>com.baomidougroupId>
<artifactId>mybatis-plus-boot-starterartifactId>
<version>${mybatis.plus.version}version>
dependency>
<dependency>
<groupId>com.baomidougroupId>
<artifactId>mybatis-plusartifactId>
<version>${mybatis.plus.version}version>
dependency>
<dependency>
<groupId>com.baomidougroupId>
<artifactId>mybatis-plus-generatorartifactId>
<version>${mybatis.plus.version}version>
dependency>
<dependency>
<groupId>org.apache.velocitygroupId>
<artifactId>velocity-engine-coreartifactId>
<version>2.2version>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<optional>trueoptional>
dependency>
<dependency>
<groupId>com.google.guavagroupId>
<artifactId>guavaartifactId>
<version>${guava.version}version>
dependency>
<dependency>
<groupId>com.github.xiaoymingroupId>
<artifactId>knife4j-spring-boot-starterartifactId>
<version>${knife4j.version}version>
dependency>
<dependency>
<groupId>com.github.xiaoymingroupId>
<artifactId>knife4j-aggregation-spring-boot-starterartifactId>
<version>${knife4j.version}version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>fastjsonartifactId>
<version>${fastjson.version}version>
dependency>
dependencies>
<build>
build>
project>
package com.xiaoxian.mybatisplusgenerator;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
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.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.FileType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import lombok.extern.slf4j.Slf4j;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Slf4j
public class CodeGenerator {
public static void generator(String projectPath, String projectName, String modulename, String mysqlUrl, String username, String password, String tableNams, String tablePrefix,
String superEntityClass) {
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
modulename = modulename == null ? "" : modulename;
// 全局配置
GlobalConfig gc = new GlobalConfig();
gc.setOutputDir("/src/main/java");
gc.setFileOverride(true);
gc.setActiveRecord(true);
gc.setEnableCache(false);// XML 二级缓存
gc.setBaseResultMap(true);// XML ResultMap
gc.setBaseColumnList(true);// XML columList
gc.setAuthor("xiaoxian");
gc.setOpen(false);
gc.setSwagger2(true);
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://" + mysqlUrl + "?autoReconnect=true&useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&zeroDateTimeBehavior=convertToNull&useSSL=false");
dsc.setDriverName("com.mysql.jdbc.Driver");
dsc.setUsername(username);
dsc.setPassword(password);
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setModuleName(modulename);
pc.setParent("com.xiaoxian." + projectName);
pc.setEntity("entity");
pc.setXml("mapper");
pc.setMapper("mapper");
pc.setService("service");
pc.setServiceImpl("service.impl");
pc.setController("controller");
Map<String, String> map = new HashMap();
map.put(ConstVal.ENTITY_PATH, projectPath + gc.getOutputDir() + "/com/xiaoxian/" + "/" + projectName + modulename + "/entity");
map.put(ConstVal.SERVICE_PATH, projectPath + gc.getOutputDir() + "/com/xiaoxian/" + "/" + projectName + modulename + "/service");
map.put(ConstVal.SERVICE_IMPL_PATH, projectPath + gc.getOutputDir() + "/com/xiaoxian/" + projectName + "/" + modulename + "/service/impl");
map.put(ConstVal.MAPPER_PATH, projectPath + gc.getOutputDir() + "/com/xiaoxian/" + "/" + projectName + modulename + "/mapper");
map.put(ConstVal.XML_PATH, projectPath + "/src/main/resources/mapper");
map.put(ConstVal.CONTROLLER_PATH, projectPath + gc.getOutputDir() + "/com/xiaoxian/" + "/" + projectName + modulename + "/controller");
pc.setPathInfo(map);
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/"
+ "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
}
});
cfg.setFileCreate(new IFileCreate() {
@Override
public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
// 判断自定义文件夹是否需要创建
checkDir(filePath);
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);
strategy.setSuperEntityClass(superEntityClass);
strategy.setEntityLombokModel(true);
strategy.setRestControllerStyle(true);
// 公共父类
// strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!");
// 写于父类中的公共字段
strategy.setSuperEntityColumns("id", "version", "is_delete", "create_time", "update_time", "update_user", "create_user");
strategy.setInclude(tableNams.split(","));
strategy.setControllerMappingHyphenStyle(true);
strategy.setTablePrefix(tablePrefix);
mpg.setStrategy(strategy);
// mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
}
public static void main(String[] args) {
//生成在当前项目路径
String projectPath = System.getProperty("user.dir");
generator(
projectPath,
"mybatisplusgenerator",
"",
"127.0.0.1:3306/test",
"root",
"123456",
"user",
"t_",
"com.xiaoxian.mybatisplusgenerator.common.BaseEntity"
);
}
}
package com.xiaoxian.mybatisplusgenerator;
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import lombok.extern.slf4j.Slf4j;
import java.util.HashMap;
import java.util.Map;
@Slf4j
public class CodeGeneratorNew {
public static void generator(String projectPath, String projectName, String modulename, String mysqlUrl, String username, String password, String tableNams, String tablePrefix,
String superEntityClass) {
String javaDir = projectPath + "/src/main/java";
String resourcesDir = projectPath + "/src/main/resources";
Map<OutputFile, String> map = new HashMap();
map.put(OutputFile.entity, javaDir + "/com/xiaoxian/" + "/" + projectName + modulename + "/entity");
map.put(OutputFile.service, javaDir + "/com/xiaoxian/" + "/" + projectName + modulename + "/service");
map.put(OutputFile.serviceImpl, javaDir + "/com/xiaoxian/" + projectName + "/" + modulename + "/service/impl");
map.put(OutputFile.mapper, javaDir + "/com/xiaoxian/" + "/" + projectName + modulename + "/mapper");
map.put(OutputFile.mapperXml, resourcesDir + "/mapper");
map.put(OutputFile.controller, javaDir + "/com/xiaoxian/" + "/" + projectName + modulename + "/controller");
FastAutoGenerator.create("jdbc:mysql://" + mysqlUrl + "?autoReconnect=true&useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&zeroDateTimeBehavior=convertToNull&useSSL=false", username, password)
.globalConfig(builder -> {
builder.author("xiaoxiao") // 设置作者
.enableSwagger() // 开启 swagger 模式
.fileOverride() // 覆盖已生成文件
.outputDir(javaDir); // 指定输出目录
})
.packageConfig(builder -> {
builder.parent("com.xiaoxian.mybatisplusgenerator") // 设置父包名
.entity("entity")
.mapper("mapper")
.moduleName("") // 设置父包模块名
.pathInfo(map); // 设置mapperXml生成路径
})
.strategyConfig(builder -> {
builder.addInclude("user") // 设置需要生成的表名
.addTablePrefix("cms_", "c_") // 设置过滤表前缀
.entityBuilder().enableLombok().enableChainModel().enableActiveRecord().superClass(superEntityClass)
;
})
// .templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板,默认的是Velocity引擎模板
.execute();
}
public static void main(String[] args) {
//生成在当前项目路径
String projectPath = System.getProperty("user.dir");
generator(
projectPath,
"mybatisplusgenerator",
"",
"127.0.0.1:3306/xiaoxian",
"root",
"123456",
"user",
"t_",
"com.xiaoxian.mybatisplusgenerator.common.BaseEntity"
);
}
}
package com.xiaoxian.mybatisplusgenerator;
import com.xiaoxian.mybatisplusgenerator.service.IUserService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class ApplicationTests {
@Autowired
IUserService userService;
@Test
void list() {
System.out.println(userService.list());
}
}