热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

MybatisPlus代码生成器/根据表生成代码使用/教程/实例

原文网址:Mybatis-Plus--代码生成器根据表生成代码--使用教程实例_IT利刃出鞘的博客-CSDN博客简介说明本文用实例介绍MybatisPlus的代码

原文网址:Mybatis-Plus--代码生成器/根据表生成代码--使用/教程/实例_IT利刃出鞘的博客-CSDN博客


简介

说明

        本文用实例介绍MybatisPlus的代码生成器。

        MybatisPlus的代码生成器很好用,可以根据表来生成Entity、Mapper、Service、Controller,非常方便,只需要配置数据库信息然后运行代码即可。

        默认就可以生成Entity、Mapper、Service、Controller,当然也可以自定义格式,本文将介绍默认格式的方法以及自定义格式的方法。

        掌握了本文介绍的生成器的方法,可以将其应用到很多根据数据库生成代码的场景,比如:JPA等。

官网

代码生成器 | MyBatis-Plus
代码生成器配置 | MyBatis-Plus


用法1:自定义格式


步骤1:搭建

创建表结构

pom.xml


4.0.0org.exampleGenerateCode1.0-SNAPSHOTcom.baomidoumybatis-plus-generator3.4.0org.freemarkerfreemarker2.3.30org.slf4jslf4j-api1.7.30org.slf4jslf4j-simple1.7.30mysqlmysql-connector-java8.0.21

因为我后边用的是freemarker(.ftl)作为模板,所以引入freemarker依赖。

后缀的含义:.ftl:freemarker;.vm:velocity;.btl:beetl。

其他两种格式的依赖为:

compile "org.apache.velocity:velocity-engine-core:2.2"
compile "com.ibeetl:beetl:3.1.8.RELEASE"

步骤2:放置模板

找到mybatis-plus-generater依赖包,查看它的模板文件:templates下边都是模板文件

本处使用.ftl文件(freemarker格式)进行修改。 修改后放到resources目录下的template_mp文件夹下


修改后的格式

MyController.java.ftl


import org.springframework.web.bind.annotation.RequestMapping;
<#if restControllerStyle>
import org.springframework.web.bind.annotation.RestController;
<#else>
import org.springframework.stereotype.Controller;

<#if superControllerClassPackage??>
import ${superControllerClassPackage};
<#if restControllerStyle>
&#64;RestController
<#else>
&#64;Controller

&#64;RequestMapping("<#if package.ModuleName?? && package.ModuleName !&#61; "">/${package.ModuleName}/<#if controllerMappingHyphenStyle??>${controllerMappingHyphen}<#else>${table.entityPath}")
<#if kotlin>
class ${table.controllerName}<#if superControllerClass??> : ${superControllerClass}()
<#else><#if superControllerClass??>
public class ${table.controllerName} extends ${superControllerClass} {<#else>
public class ${table.controllerName} {}

MyService.java.ftl


import ${superServiceClassPackage};<#if kotlin>
interface ${table.serviceName} : ${superServiceClass}<${entity}>
<#else>
public interface ${table.serviceName} extends ${superServiceClass}<${entity}> {}

MyServiceImpl.java.ftl


import ${superServiceImplClassPackage};
import org.springframework.stereotype.Service;&#64;Service
<#if kotlin>
open class ${table.serviceImplName} : ${superServiceImplClass}<${table.mapperName}, ${entity}>(), ${table.serviceName} {}
<#else>
public class ${table.serviceImplName} extends ${superServiceImplClass}<${table.mapperName}, ${entity}> implements ${table.serviceName} {}

MyMapper.java.ftl


import ${superMapperClassPackage};&#64;Repository
<#if kotlin>
interface ${table.mapperName} : ${superMapperClass}<${entity}>
<#else>
public interface ${table.mapperName} extends ${superMapperClass}<${entity}> {}

MyEntity.java.ftl


<#list table.importPackages as pkg>
import ${pkg};

<#if swagger2>
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

<#if entityLombokModel>
import lombok.Data;
import lombok.EqualsAndHashCode;<#if chainModel>
import lombok.experimental.Accessors;
<#if entityLombokModel>
&#64;Data<#if superEntityClass??>
&#64;EqualsAndHashCode(callSuper &#61; true)<#else>
&#64;EqualsAndHashCode(callSuper &#61; false)<#if chainModel>
&#64;Accessors(chain &#61; true)

<#if table.convert>
&#64;TableName("${table.name}")

<#if swagger2>
&#64;ApiModel(value&#61;"${entity}对象", description&#61;"${table.comment!}")

<#if superEntityClass??>
public class ${entity} extends ${superEntityClass}<#if activeRecord><${entity}> {
<#elseif activeRecord>
public class ${entity} extends Model<${entity}> {
<#else>
public class ${entity} {

<#-- ---------- BEGIN 字段循环遍历 ---------->
<#list table.fields as field><#if field.keyFlag><#assign keyPropertyName&#61;"${field.propertyName}"/><#if field.comment!?length gt 0><#if swagger2>&#64;ApiModelProperty(value &#61; "${field.comment}")<#else>// ${field.comment}<#if field.keyFlag><#-- 主键 --><#if field.keyIdentityFlag>&#64;TableId(value &#61; "${field.annotationColumnName}", type &#61; IdType.AUTO)<#elseif idType??>&#64;TableId(value &#61; "${field.annotationColumnName}", type &#61; IdType.${idType})<#elseif field.convert>&#64;TableId("${field.annotationColumnName}")<#-- 普通字段 --><#elseif field.fill??><#-- ----- 存在字段填充设置 -----><#if field.convert>&#64;TableField(value &#61; "${field.annotationColumnName}", fill &#61; FieldFill.${field.fill})<#else>&#64;TableField(fill &#61; FieldFill.${field.fill})<#elseif field.convert>&#64;TableField("${field.annotationColumnName}")
<#-- 乐观锁注解 --><#if (versionFieldName!"") &#61;&#61; field.name>&#64;Version
<#-- 逻辑删除注解 --><#if (logicDeleteFieldName!"") &#61;&#61; field.name>&#64;TableLogicprivate ${field.propertyType} ${field.propertyName};
<#------------ END 字段循环遍历 ---------->
<#if !entityLombokModel><#list table.fields as field><#if field.propertyType &#61;&#61; "boolean"><#assign getprefix&#61;"is"/><#else><#assign getprefix&#61;"get"/>public ${field.propertyType} ${getprefix}${field.capitalName}() {return ${field.propertyName};}<#if chainModel>public ${entity} set${field.capitalName}(${field.propertyType} ${field.propertyName}) {<#else>public void set${field.capitalName}(${field.propertyType} ${field.propertyName}) {this.${field.propertyName} &#61; ${field.propertyName};<#if chainModel>return this;}

<#if entityColumnConstant><#list table.fields as field>public static final String ${field.name?upper_case} &#61; "${field.name}";

<#if activeRecord>&#64;Overrideprotected Serializable pkVal() {<#if keyPropertyName??>return this.${keyPropertyName};<#else>return null;}

<#if !entityLombokModel>&#64;Overridepublic String toString() {return "${entity}{" &#43;<#list table.fields as field><#if field_index&#61;&#61;0>"${field.propertyName}&#61;" &#43; ${field.propertyName} &#43;<#else>", ${field.propertyName}&#61;" &#43; ${field.propertyName} &#43;"}";}

}

原来的格式

controller.java.ftl

package ${package.Controller};import org.springframework.web.bind.annotation.RequestMapping;<#if restControllerStyle>
import org.springframework.web.bind.annotation.RestController;
<#else>
import org.springframework.stereotype.Controller;

<#if superControllerClassPackage??>
import ${superControllerClassPackage};
/***

* ${table.comment!} 前端控制器*

** &#64;author ${author}* &#64;since ${date}*/
<#if restControllerStyle>
&#64;RestController
<#else>
&#64;Controller

&#64;RequestMapping("<#if package.ModuleName?? && package.ModuleName !&#61; "">/${package.ModuleName}/<#if controllerMappingHyphenStyle??>${controllerMappingHyphen}<#else>${table.entityPath}")
<#if kotlin>
class ${table.controllerName}<#if superControllerClass??> : ${superControllerClass}()
<#else>
<#if superControllerClass??>
public class ${table.controllerName} extends ${superControllerClass} {
<#else>
public class ${table.controllerName} {
}

service.java.ftl

package ${package.Service};import ${package.Entity}.${entity};
import ${superServiceClassPackage};/***

* ${table.comment!} 服务类*

** &#64;author ${author}* &#64;since ${date}*/
<#if kotlin>
interface ${table.serviceName} : ${superServiceClass}<${entity}>
<#else>
public interface ${table.serviceName} extends ${superServiceClass}<${entity}> {}

serviceImpl.java.ftl

package ${package.ServiceImpl};import ${package.Entity}.${entity};
import ${package.Mapper}.${table.mapperName};
import ${package.Service}.${table.serviceName};
import ${superServiceImplClassPackage};
import org.springframework.stereotype.Service;/***

* ${table.comment!} 服务实现类*

** &#64;author ${author}* &#64;since ${date}*/
&#64;Service
<#if kotlin>
open class ${table.serviceImplName} : ${superServiceImplClass}<${table.mapperName}, ${entity}>(), ${table.serviceName} {}
<#else>
public class ${table.serviceImplName} extends ${superServiceImplClass}<${table.mapperName}, ${entity}> implements ${table.serviceName} {}

 mapper.java.ftl

package ${package.Mapper};import ${package.Entity}.${entity};
import ${superMapperClassPackage};/***

* ${table.comment!} Mapper 接口*

** &#64;author ${author}* &#64;since ${date}*/
<#if kotlin>
interface ${table.mapperName} : ${superMapperClass}<${entity}>
<#else>
public interface ${table.mapperName} extends ${superMapperClass}<${entity}> {}

entity.java.ftl

package ${package.Entity};<#list table.importPackages as pkg>
import ${pkg};

<#if swagger2>
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

<#if entityLombokModel>
import lombok.Data;
import lombok.EqualsAndHashCode;<#if chainModel>
import lombok.experimental.Accessors;
/***

* ${table.comment!}*

** &#64;author ${author}* &#64;since ${date}*/
<#if entityLombokModel>
&#64;Data<#if superEntityClass??>
&#64;EqualsAndHashCode(callSuper &#61; true)<#else>
&#64;EqualsAndHashCode(callSuper &#61; false)<#if chainModel>
&#64;Accessors(chain &#61; true)

<#if table.convert>
&#64;TableName("${table.name}")

<#if swagger2>
&#64;ApiModel(value&#61;"${entity}对象", description&#61;"${table.comment!}")

<#if superEntityClass??>
public class ${entity} extends ${superEntityClass}<#if activeRecord><${entity}> {
<#elseif activeRecord>
public class ${entity} extends Model<${entity}> {
<#else>
public class ${entity} implements Serializable {
<#if entitySerialVersionUID>private static final long serialVersionUID &#61; 1L;

<#-- ---------- BEGIN 字段循环遍历 ---------->
<#list table.fields as field><#if field.keyFlag><#assign keyPropertyName&#61;"${field.propertyName}"/><#if field.comment!?length gt 0><#if swagger2>&#64;ApiModelProperty(value &#61; "${field.comment}")<#else>/*** ${field.comment}*/<#if field.keyFlag><#-- 主键 --><#if field.keyIdentityFlag>&#64;TableId(value &#61; "${field.annotationColumnName}", type &#61; IdType.AUTO)<#elseif idType??>&#64;TableId(value &#61; "${field.annotationColumnName}", type &#61; IdType.${idType})<#elseif field.convert>&#64;TableId("${field.annotationColumnName}")<#-- 普通字段 --><#elseif field.fill??><#-- ----- 存在字段填充设置 -----><#if field.convert>&#64;TableField(value &#61; "${field.annotationColumnName}", fill &#61; FieldFill.${field.fill})<#else>&#64;TableField(fill &#61; FieldFill.${field.fill})<#elseif field.convert>&#64;TableField("${field.annotationColumnName}")<#-- 乐观锁注解 --><#if (versionFieldName!"") &#61;&#61; field.name>&#64;Version<#-- 逻辑删除注解 --><#if (logicDeleteFieldName!"") &#61;&#61; field.name>&#64;TableLogicprivate ${field.propertyType} ${field.propertyName};

<#------------ END 字段循环遍历 ----------><#if !entityLombokModel><#list table.fields as field><#if field.propertyType &#61;&#61; "boolean"><#assign getprefix&#61;"is"/><#else><#assign getprefix&#61;"get"/>public ${field.propertyType} ${getprefix}${field.capitalName}() {return ${field.propertyName};}<#if chainModel>public ${entity} set${field.capitalName}(${field.propertyType} ${field.propertyName}) {<#else>public void set${field.capitalName}(${field.propertyType} ${field.propertyName}) {this.${field.propertyName} &#61; ${field.propertyName};<#if chainModel>return this;}
<#if entityColumnConstant><#list table.fields as field>public static final String ${field.name?upper_case} &#61; "${field.name}";

<#if activeRecord>&#64;Overrideprotected Serializable pkVal() {<#if keyPropertyName??>return this.${keyPropertyName};<#else>return null;}
<#if !entityLombokModel>&#64;Overridepublic String toString() {return "${entity}{" &#43;<#list table.fields as field><#if field_index&#61;&#61;0>"${field.propertyName}&#61;" &#43; ${field.propertyName} &#43;<#else>", ${field.propertyName}&#61;" &#43; ${field.propertyName} &#43;"}";}

}

步骤3&#xff1a;提供主类

package com.example.generate;import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;public class Generate {private static final String url &#61; "jdbc:mysql://127.0.0.1:3306/blog" &#43;"?useUnicode&#61;true&characterEncoding&#61;utf8" &#43;"&allowPublicKeyRetrieval&#61;True&useSSL&#61;false" &#43;"&serverTimezone&#61;Asia/Shanghai";private static final String userName &#61; "root";private static final String password &#61; "222333";private static final String tableName &#61; "t_blog";private static final String tablePrefix &#61; "t_";// 演示例子public static void main(String[] args) {// 代码生成器AutoGenerator autoGenerator &#61; new AutoGenerator();// 全局配置GlobalConfig globalConfig &#61; new GlobalConfig();String projectPath &#61; System.getProperty("user.dir");globalConfig.setOutputDir(projectPath &#43; "/src/main/java");globalConfig.setAuthor("xxx");globalConfig.setFileOverride(false); //默认就是falseglobalConfig.setOpen(false);// gc.setBaseResultMap(true); // mapper.xml 生成 ResultMap// gc.setBaseColumnList(true); // mapper.xml 生成 ColumnList// 自定义文件命名&#xff0c;注意 %s 会自动填充表实体属性&#xff01;globalConfig.setMapperName("%sMapper");// gc.setXmlName("%sDao");globalConfig.setServiceName("%sService");globalConfig.setServiceImplName("%sServiceImpl");globalConfig.setControllerName("%sController");// gc.setSwagger2(true); 实体属性 Swagger2 注解autoGenerator.setGlobalConfig(globalConfig);// 数据源配置DataSourceConfig dataSourceConfig &#61; new DataSourceConfig();dataSourceConfig.setUrl(url);// dsc.setSchemaName("public");dataSourceConfig.setDriverName("com.mysql.cj.jdbc.Driver");dataSourceConfig.setUsername(userName);dataSourceConfig.setPassword(password);autoGenerator.setDataSource(dataSourceConfig);// 包配置PackageConfig packageConfig &#61; new PackageConfig();// pc.setParent("com.example.generate.out");// pc.setModuleName("xxx");packageConfig.setParent("com.example.generate." &#43; tableName.substring(tablePrefix.length()));autoGenerator.setPackageInfo(packageConfig);// 自定义配置// InjectionConfig cfg &#61; new InjectionConfig() {// &#64;Override// public void initMap() {// // to do nothing// }// };// 配置自定义输出模板TemplateConfig templateConfig &#61; new TemplateConfig();//指定自定义模板路径&#xff0c;注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别templateConfig.setController("templates_mp/MyController.java");templateConfig.setService("templates_mp/MyService.java");templateConfig.setServiceImpl("templates_mp/MyServiceImpl.java");templateConfig.setMapper("templates_mp/MyMapper.java");templateConfig.setEntity("templates_mp/MyEntity.java");templateConfig.setXml(null);autoGenerator.setTemplate(templateConfig);// 策略配置StrategyConfig strategyConfig &#61; new StrategyConfig();strategyConfig.setNaming(NamingStrategy.underline_to_camel);strategyConfig.setColumnNaming(NamingStrategy.underline_to_camel);//strategy.setSuperEntityClass("你自己的父类实体,没有就不用设置!");strategyConfig.setEntityLombokModel(true);strategyConfig.setRestControllerStyle(true);// 公共父类// strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!");// 写于父类中的公共字段// strategy.setSuperEntityColumns("id");// 表名strategyConfig.setInclude(tableName);strategyConfig.setTablePrefix(tablePrefix);autoGenerator.setStrategy(strategyConfig);strategyConfig.setControllerMappingHyphenStyle(true);autoGenerator.setTemplateEngine(new FreemarkerTemplateEngine());autoGenerator.execute();}
}

步骤4&#xff1a;运行主类

将“步骤3”代码放到任意位置运行即可。

运行之前

运行之后

红框中是新生成的文件


用法2&#xff1a;使用默认格式


步骤1&#xff1a;搭建

创建表结构

步骤2&#xff1a;引入依赖

compile "com.baomidou:mybatis-plus-generator:3.4.0"
compile "org.slf4j:slf4j-api:1.7.30"
compile "org.slf4j:slf4j-simple:1.7.30"
compile "mysql:mysql-connector-java:8.0.21"

步骤2&#xff1a;提供主类

package com.example.generate;import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;public class Generate {private static final String url &#61; "jdbc:mysql://127.0.0.1:3306/blog" &#43;"?useUnicode&#61;true&characterEncoding&#61;utf8" &#43;"&allowPublicKeyRetrieval&#61;True&useSSL&#61;false" &#43;"&serverTimezone&#61;Asia/Shanghai";private static final String userName &#61; "root";private static final String password &#61; "222333";private static final String tableName &#61; "t_blog";private static final String tablePrefix &#61; "t_";// 演示例子public static void main(String[] args) {// 代码生成器AutoGenerator autoGenerator &#61; new AutoGenerator();// 全局配置GlobalConfig globalConfig &#61; new GlobalConfig();String projectPath &#61; System.getProperty("user.dir");globalConfig.setOutputDir(projectPath &#43; "/src/main/java");globalConfig.setAuthor("xxx");globalConfig.setFileOverride(false); //默认就是falseglobalConfig.setOpen(false);// gc.setBaseResultMap(true); // mapper.xml 生成 ResultMap// gc.setBaseColumnList(true); // mapper.xml 生成 ColumnList// 自定义文件命名&#xff0c;注意 %s 会自动填充表实体属性&#xff01;globalConfig.setMapperName("%sMapper");// gc.setXmlName("%sDao");globalConfig.setServiceName("%sService");globalConfig.setServiceImplName("%sServiceImpl");globalConfig.setControllerName("%sController");// gc.setSwagger2(true); 实体属性 Swagger2 注解autoGenerator.setGlobalConfig(globalConfig);// 数据源配置DataSourceConfig dataSourceConfig &#61; new DataSourceConfig();dataSourceConfig.setUrl(url);// dsc.setSchemaName("public");dataSourceConfig.setDriverName("com.mysql.cj.jdbc.Driver");dataSourceConfig.setUsername(userName);dataSourceConfig.setPassword(password);autoGenerator.setDataSource(dataSourceConfig);// 包配置PackageConfig packageConfig &#61; new PackageConfig();// pc.setParent("com.example.generate.out");// pc.setModuleName("xxx");packageConfig.setParent("com.example.generate." &#43; tableName.substring(tablePrefix.length()));autoGenerator.setPackageInfo(packageConfig);// 自定义配置// InjectionConfig cfg &#61; new InjectionConfig() {// &#64;Override// public void initMap() {// // to do nothing// }// };// // 配置自定义输出模板// TemplateConfig templateConfig &#61; new TemplateConfig();// //指定自定义模板路径&#xff0c;注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别// templateConfig.setController("templates_mp/MyController.java");// templateConfig.setService("templates_mp/MyService.java");// templateConfig.setServiceImpl("templates_mp/MyServiceImpl.java");// templateConfig.setMapper("templates_mp/MyMapper.java");// templateConfig.setEntity("templates_mp/MyEntity.java");// templateConfig.setXml(null);// autoGenerator.setTemplate(templateConfig);// 策略配置StrategyConfig strategyConfig &#61; new StrategyConfig();strategyConfig.setNaming(NamingStrategy.underline_to_camel);strategyConfig.setColumnNaming(NamingStrategy.underline_to_camel);//strategy.setSuperEntityClass("你自己的父类实体,没有就不用设置!");strategyConfig.setEntityLombokModel(true);strategyConfig.setRestControllerStyle(true);// 公共父类// strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!");// 写于父类中的公共字段// strategy.setSuperEntityColumns("id");// 表名strategyConfig.setInclude(tableName);strategyConfig.setTablePrefix(tablePrefix);autoGenerator.setStrategy(strategyConfig);strategyConfig.setControllerMappingHyphenStyle(true);autoGenerator.setTemplateEngine(new FreemarkerTemplateEngine());autoGenerator.execute();}
}

步骤3&#xff1a;运行主类

此“步骤2”代码放到任意位置运行即可。


其他


带mapper(xml)的主类

import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
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.converts.MySqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
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.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;// 演示例子&#xff0c;执行 main 方法控制台输入模块表名回车自动生成对应项目目录中
public class CodeGenerator {public static void main(String[] args) {// 代码生成器AutoGenerator mpg &#61; new AutoGenerator();// 全局配置GlobalConfig gc &#61; new GlobalConfig();String projectPath &#61; System.getProperty("user.dir");gc.setOutputDir(projectPath &#43; "/src/main/java");gc.setAuthor("xxx"); gc.setOpen(false);/* 自定义文件命名&#xff0c;注意 %s 会自动填充表实体属性&#xff01; */gc.setMapperName("%sMapper");// gc.setXmlName("%sDao");gc.setServiceName("%sService");gc.setServiceImplName("%sServiceImpl");gc.setControllerName("%sController");// gc.setSwagger2(true); 实体属性 Swagger2 注解mpg.setGlobalConfig(gc);// 数据源配置DataSourceConfig dsc &#61; new DataSourceConfig();dsc.setUrl("xxx");// dsc.setSchemaName("public");dsc.setDriverName("com.mysql.cj.jdbc.Driver");dsc.setUsername("xxx"); dsc.setPassword("xxx"); mpg.setDataSource(dsc);// 包配置PackageConfig pc &#61; new PackageConfig();// pc.setModuleName(scanner("模块名"));pc.setParent("xxx"); mpg.setPackageInfo(pc);// 自定义配置InjectionConfig cfg &#61; new InjectionConfig() {&#64;Overridepublic void initMap() {// to do nothing}};// 输出resources/mapper// 如果模板引擎是 freemarkerString templatePath &#61; "/templates/mapper.xml.ftl";// 如果模板引擎是 velocity// String templatePath &#61; "/templates/mapper.xml.vm";// 自定义输出配置List focList &#61; new ArrayList<>();// 自定义配置会被优先输出focList.add(new FileOutConfig(templatePath) {&#64;Overridepublic String outputFile(TableInfo tableInfo) {// 自定义输出文件名 &#xff0c; 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化&#xff01;&#xff01;return projectPath &#43; "/src/main/resources/mapper/" &#43; pc.getModuleName()&#43; "/" &#43; tableInfo.getEntityName() &#43; "Mapper" &#43; StringPool.DOT_XML;}});cfg.setFileCreate(new IFileCreate() {&#64;Overridepublic boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {// 判断自定义文件夹是否需要创建checkDir("调用默认方法创建的目录&#xff0c;自定义目录用");if (fileType &#61;&#61; FileType.MAPPER) {// 已经生成 mapper 文件判断存在&#xff0c;不想重新生成返回 falsereturn !new File(filePath).exists();}// 允许生成模板文件return true;}});cfg.setFileOutConfigList(focList);mpg.setCfg(cfg);// 配置模板TemplateConfig templateConfig &#61; new TemplateConfig();// 配置自定义输出模板//指定自定义模板路径&#xff0c;注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别// templateConfig.setEntity("templates/entity2.java");// templateConfig.setService();// templateConfig.setController();templateConfig.setXml(null);mpg.setTemplate(templateConfig);// 策略配置StrategyConfig strategy &#61; new StrategyConfig();strategy.setNaming(NamingStrategy.underline_to_camel);strategy.setColumnNaming(NamingStrategy.underline_to_camel);//strategy.setSuperEntityClass("你自己的父类实体,没有就不用设置!");strategy.setEntityLombokModel(true);strategy.setRestControllerStyle(true);// 公共父类//strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!");// 写于父类中的公共字段strategy.setSuperEntityColumns("id");strategy.setInclude("xxx");strategy.setControllerMappingHyphenStyle(true);strategy.setTablePrefix("t_"); mpg.setStrategy(strategy);mpg.setTemplateEngine(new FreemarkerTemplateEngine());mpg.execute();}
}

其他网址

MyBatis-Plus代码生成器 - 掘金
MyBatisPlus 3.x 代码生成器 - 简书
Mybatis Plus————代码生成器_燃烧的小宇宙-CSDN博客

自定义模板

自定义代码生成器模板 - MyBatis Plus 教程
MybatisPlus自定义模版中能获取到的信息_开发者的博客-CSDN博客


推荐阅读
  • Java实战之电影在线观看系统的实现
    本文介绍了Java实战之电影在线观看系统的实现过程。首先对项目进行了简述,然后展示了系统的效果图。接着介绍了系统的核心代码,包括后台用户管理控制器、电影管理控制器和前台电影控制器。最后对项目的环境配置和使用的技术进行了说明,包括JSP、Spring、SpringMVC、MyBatis、html、css、JavaScript、JQuery、Ajax、layui和maven等。 ... [详细]
  • flowable工作流 流程变量_信也科技工作流平台的技术实践
    1背景随着公司业务发展及内部业务流程诉求的增长,目前信息化系统不能够很好满足期望,主要体现如下:目前OA流程引擎无法满足企业特定业务流程需求,且移动端体 ... [详细]
  • Activiti7流程定义开发笔记
    本文介绍了Activiti7流程定义的开发笔记,包括流程定义的概念、使用activiti-explorer和activiti-eclipse-designer进行建模的方式,以及生成流程图的方法。还介绍了流程定义部署的概念和步骤,包括将bpmn和png文件添加部署到activiti数据库中的方法,以及使用ZIP包进行部署的方式。同时还提到了activiti.cfg.xml文件的作用。 ... [详细]
  • 大数据Hadoop生态(20)MapReduce框架原理OutputFormat的开发笔记
    本文介绍了大数据Hadoop生态(20)MapReduce框架原理OutputFormat的开发笔记,包括outputFormat接口实现类、自定义outputFormat步骤和案例。案例中将包含nty的日志输出到nty.log文件,其他日志输出到other.log文件。同时提供了一些相关网址供参考。 ... [详细]
  • SpringBoot uri统一权限管理的实现方法及步骤详解
    本文详细介绍了SpringBoot中实现uri统一权限管理的方法,包括表结构定义、自动统计URI并自动删除脏数据、程序启动加载等步骤。通过该方法可以提高系统的安全性,实现对系统任意接口的权限拦截验证。 ... [详细]
  • 本文介绍了Java工具类库Hutool,该工具包封装了对文件、流、加密解密、转码、正则、线程、XML等JDK方法的封装,并提供了各种Util工具类。同时,还介绍了Hutool的组件,包括动态代理、布隆过滤、缓存、定时任务等功能。该工具包可以简化Java代码,提高开发效率。 ... [详细]
  • Java容器中的compareto方法排序原理解析
    本文从源码解析Java容器中的compareto方法的排序原理,讲解了在使用数组存储数据时的限制以及存储效率的问题。同时提到了Redis的五大数据结构和list、set等知识点,回忆了作者大学时代的Java学习经历。文章以作者做的思维导图作为目录,展示了整个讲解过程。 ... [详细]
  • 本文介绍了在SpringBoot中集成thymeleaf前端模版的配置步骤,包括在application.properties配置文件中添加thymeleaf的配置信息,引入thymeleaf的jar包,以及创建PageController并添加index方法。 ... [详细]
  • 本文介绍了在Mac上搭建php环境后无法使用localhost连接mysql的问题,并通过将localhost替换为127.0.0.1或本机IP解决了该问题。文章解释了localhost和127.0.0.1的区别,指出了使用socket方式连接导致连接失败的原因。此外,还提供了相关链接供读者深入了解。 ... [详细]
  • XML介绍与使用的概述及标签规则
    本文介绍了XML的基本概念和用途,包括XML的可扩展性和标签的自定义特性。同时还详细解释了XML标签的规则,包括标签的尖括号和合法标识符的组成,标签必须成对出现的原则以及特殊标签的使用方法。通过本文的阅读,读者可以对XML的基本知识有一个全面的了解。 ... [详细]
  • 本文介绍了如何使用C#制作Java+Mysql+Tomcat环境安装程序,实现一键式安装。通过将JDK、Mysql、Tomcat三者制作成一个安装包,解决了客户在安装软件时的复杂配置和繁琐问题,便于管理软件版本和系统集成。具体步骤包括配置JDK环境变量和安装Mysql服务,其中使用了MySQL Server 5.5社区版和my.ini文件。安装方法为通过命令行将目录转到mysql的bin目录下,执行mysqld --install MySQL5命令。 ... [详细]
  • r2dbc配置多数据源
    R2dbc配置多数据源问题根据官网配置r2dbc连接mysql多数据源所遇到的问题pom配置可以参考官网,不过我这样配置会报错我并没有这样配置将以下内容添加到pom.xml文件d ... [详细]
  • 本文介绍了使用cacti监控mssql 2005运行资源情况的操作步骤,包括安装必要的工具和驱动,测试mssql的连接,配置监控脚本等。通过php连接mssql来获取SQL 2005性能计算器的值,实现对mssql的监控。详细的操作步骤和代码请参考附件。 ... [详细]
  • 本文介绍了如何使用JSONObiect和Gson相关方法实现json数据与kotlin对象的相互转换。首先解释了JSON的概念和数据格式,然后详细介绍了相关API,包括JSONObject和Gson的使用方法。接着讲解了如何将json格式的字符串转换为kotlin对象或List,以及如何将kotlin对象转换为json字符串。最后提到了使用Map封装json对象的特殊情况。文章还对JSON和XML进行了比较,指出了JSON的优势和缺点。 ... [详细]
  • 本文介绍了使用Spark实现低配版高斯朴素贝叶斯模型的原因和原理。随着数据量的增大,单机上运行高斯朴素贝叶斯模型会变得很慢,因此考虑使用Spark来加速运行。然而,Spark的MLlib并没有实现高斯朴素贝叶斯模型,因此需要自己动手实现。文章还介绍了朴素贝叶斯的原理和公式,并对具有多个特征和类别的模型进行了讨论。最后,作者总结了实现低配版高斯朴素贝叶斯模型的步骤。 ... [详细]
author-avatar
温德军46867
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有