分享myBatis-plus代碼生成器的使用步驟以及以其為基礎(chǔ)編寫的在線crud代碼生成器
1.pom文件中配置mybatis-plus-generator
使用代碼生成器時需要先把pom文件中mybatis-plus依賴注釋掉滋尉,并引入mybatis-plus-generaor依賴和模板引擎依賴,否則寫生成器代碼時候找不到對應(yīng)的包
<!--<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.3.1.tmp</version>
</dependency>-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.3.1.tmp</version>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.2</version>
</dependency>
2.編寫代碼生成器
直接復(fù)制官方示例代碼的話需要修改代碼中使用freemarker模板引擎的地方換成velocity厂画,以下是修改后的代碼
package com.lfy.springboot;
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.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.VelocityTemplateEngine;
import java.util.ArrayList;
import java.util.List;
/**
* @Author: 李豐翼
* @DateTime: 2020/5/18 0018 19:21
* @Description: TODO
*/
public class CodeGenerator {
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("lfy");
gc.setOpen(false);
gc.setMapperName("%sDao");
gc.setXmlName("%sDao");
gc.setSwagger2(true); //實體屬性 Swagger2 注解
gc.setFileOverride(true);
gc.setBaseColumnList(true);
gc.setBaseResultMap(true);
mpg.setGlobalConfig(gc);
// 數(shù)據(jù)源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://localhost:3306/wenjuan?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false");
// dsc.setSchemaName("public");
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("root");
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setParent("com.lfy.springboot");
pc.setMapper("dao");
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<>();
// 自定義配置會被優(yōu)先輸出
focList.add(new FileOutConfig(templatePath) {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定義輸出文件名 们镜, 如果你 Entity 設(shè)置了前后綴结蟋、此處注意 xml 的名稱會跟著發(fā)生變化!!
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) {
// 判斷自定義文件夾是否需要創(chuàng)建
checkDir("調(diào)用默認(rèn)方法創(chuàng)建的目錄诚些,自定義目錄用");
if (fileType == FileType.MAPPER) {
// 已經(jīng)生成 mapper 文件判斷存在硝岗,不想重新生成返回 false
return !new File(filePath).exists();
}
// 允許生成模板文件
return true;
}
});*/
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
// 配置模板
TemplateConfig templateConfig = new TemplateConfig();
// 配置自定義輸出模板
//指定自定義模板路徑氢哮,注意不要帶上.ftl/.vm, 會根據(jù)使用的模板引擎自動識別
// 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.setEntityLombokModel(true);
strategy.setRestControllerStyle(true);
// 寫于父類中的公共字段
strategy.setSuperEntityColumns("id");
strategy.setControllerMappingHyphenStyle(true);
strategy.setTablePrefix(pc.getModuleName() + "_");
strategy.setRestControllerStyle(true);
strategy.setSuperControllerClass("com.lfy.springboot.controller.BaseController");
mpg.setStrategy(strategy);
mpg.setTemplateEngine(new VelocityTemplateEngine());
mpg.execute();
}
}
更多詳細(xì)配置參考官方文檔
https://mp.baomidou.com/config/generator-config.html#%E5%9F%BA%E6%9C%AC%E9%85%8D%E7%BD%AE
3.編寫xml模板
創(chuàng)建mapper.xml.vm放在templates目錄下,這里只寫了mapper.xml的模板型檀,其他的部分也可以自定義模板文件
可以參考https://blog.csdn.net/kanglong129/article/details/98362009
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="${package.Mapper}.${table.mapperName}">
#if(${enableCache})
<cache type="org.mybatis.caches.ehcache.LoggingEhcache"/>
#end
#if(${baseResultMap})
<resultMap id="BaseResultMap" type="${package.Entity}.${entity}">
#foreach($field in ${table.fields})
#if(${field.keyFlag})##生成主鍵排在第一位
<id column="${field.name}" property="${field.propertyName}" />
#end
#end
#foreach($field in ${table.commonFields})##生成公共字段
<result column="${field.name}" property="${field.propertyName}" />
#end
#foreach($field in ${table.fields})
#if(!${field.keyFlag})##生成普通字段
<result column="${field.name}" property="${field.propertyName}" />
#end
#end
</resultMap>
#end
<sql id="Base_Table_Name">
${table.name}
</sql>
<sql id="Base_Column_List">
#foreach($field in ${table.commonFields})
#if(${field.name} == ${field.propertyName})${field.name}#else${field.name} AS ${field.propertyName}#end,
#end
${table.fieldNames}
</sql>
</mapper>
mapper模板中可以使用的屬性可以參考源碼中com.baomidou.mybatisplus.generator.config.po.TableInfo中的屬性
/*
* Copyright (c) 2011-2020, baomidou (jobob@qq.com).
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
* <p>
* https://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.baomidou.mybatisplus.generator.config.po;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.IntStream;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import lombok.Data;
import lombok.experimental.Accessors;
/**
* 表信息冗尤,關(guān)聯(lián)到當(dāng)前字段信息
*
* @author YangHu
* @since 2016/8/30
*/
@Data
@Accessors(chain = true)
public class TableInfo {
private final Set<String> importPackages = new HashSet<>();
private boolean convert;
private String name;
private String comment;
private String entityName;
private String mapperName;
private String xmlName;
private String serviceName;
private String serviceImplName;
private String controllerName;
private List<TableField> fields;
/**
* 公共字段
*/
private List<TableField> commonFields;
private String fieldNames;
public TableInfo setConvert(boolean convert) {
this.convert = convert;
return this;
}
protected TableInfo setConvert(StrategyConfig strategyConfig) {
if (strategyConfig.containsTablePrefix(name) || strategyConfig.isEntityTableFieldAnnotationEnable()) {
// 包含前綴
this.convert = true;
} else if (strategyConfig.isCapitalModeNaming(name)) {
// 包含
this.convert = false;
} else {
// 轉(zhuǎn)換字段
if (NamingStrategy.underline_to_camel == strategyConfig.getColumnNaming()) {
// 包含大寫處理
if (StringUtils.containsUpperCase(name)) {
this.convert = true;
}
} else if (!entityName.equalsIgnoreCase(name)) {
this.convert = true;
}
}
return this;
}
public String getEntityPath() {
return entityName.substring(0, 1).toLowerCase() + entityName.substring(1);
}
public TableInfo setEntityName(StrategyConfig strategyConfig, String entityName) {
this.entityName = entityName;
this.setConvert(strategyConfig);
return this;
}
public TableInfo setFields(List<TableField> fields) {
if (CollectionUtils.isNotEmpty(fields)) {
this.fields = fields;
// 收集導(dǎo)入包信息
for (TableField field : fields) {
if (null != field.getColumnType() && null != field.getColumnType().getPkg()) {
importPackages.add(field.getColumnType().getPkg());
}
if (field.isKeyFlag()) {
// 主鍵
if (field.isConvert() || field.isKeyIdentityFlag()) {
importPackages.add(com.baomidou.mybatisplus.annotation.TableId.class.getCanonicalName());
}
// 自增
if (field.isKeyIdentityFlag()) {
importPackages.add(com.baomidou.mybatisplus.annotation.IdType.class.getCanonicalName());
}
} else if (field.isConvert()) {
// 普通字段
importPackages.add(com.baomidou.mybatisplus.annotation.TableField.class.getCanonicalName());
}
if (null != field.getFill()) {
// 填充字段
importPackages.add(com.baomidou.mybatisplus.annotation.TableField.class.getCanonicalName());
importPackages.add(com.baomidou.mybatisplus.annotation.FieldFill.class.getCanonicalName());
}
}
}
return this;
}
public TableInfo setImportPackages(String pkg) {
importPackages.add(pkg);
return this;
}
/**
* 邏輯刪除
*/
public boolean isLogicDelete(String logicDeletePropertyName) {
return fields.parallelStream().anyMatch(tf -> tf.getName().equals(logicDeletePropertyName));
}
/**
* 轉(zhuǎn)換filed實體為 xml mapper 中的 base column 字符串信息
*/
public String getFieldNames() {
if (StringUtils.isBlank(fieldNames)
&& CollectionUtils.isNotEmpty(fields)) {
StringBuilder names = new StringBuilder();
IntStream.range(0, fields.size()).forEach(i -> {
TableField fd = fields.get(i);
if (i == fields.size() - 1) {
names.append(fd.getName());
} else {
names.append(fd.getName()).append(", ");
}
});
fieldNames = names.toString();
}
return fieldNames;
}
}
4.生成的效果如下
目錄
mapper.xml文件
5.使用完畢后將pom文件中的生成器依賴注釋,改為mybatis-plus
6.學(xué)習(xí)完之后胀溺,個人根據(jù)代碼生成器編寫了一個小的在線代碼生成開源項目
Gitee地址:https://gitee.com/li_feng_yi/code-generation 求star~~
項目地址:http://generator.lifengyi.cn/