mybatis-plus代码生成器【一看就会,复制即用】

2024-05-28 17:28

本文主要是介绍mybatis-plus代码生成器【一看就会,复制即用】,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

环境

jdk 17、mysql 8、springboot 3.1.2

POM依赖

        <dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-core</artifactId><version>3.5.6</version></dependency>
<!--        mybatis-plus代码生成依赖--><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-generator</artifactId><version>3.4.1</version></dependency><dependency>
<!--            Java模板引擎--><groupId>org.apache.velocity</groupId><artifactId>velocity-engine-core</artifactId><version>2.3</version></dependency>

工具类代码

注意:使用时需要修改实际参数,比如数据库连接、数据库账号密码、表名、导出路径等


import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;/*** @description: mybatis代码生成* @author: lwj@gk.com* @create: 2024-05-28**/public class CodeGenerator {private static final String URL = "jdbc:mysql://localhost:3306/java_study?characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai"; //数据库连接private static final String OUTPUT_DIR = "F:\\outCode"; //导出路径private static final String AUTHOR = "Desmond";private static final String DRIVER_NAME = "com.mysql.cj.jdbc.Driver";private static final String USERNAME = "root";private static final String PASSWORD = "root";private static final String PARENT = "test"; //包名private static final String MODULE_NAME = "test"; //模块名private static final String TABLE_NAME = "departments"; // 表名public static void main(String[] args) {// 代码生成器AutoGenerator mpg = new AutoGenerator();// 全局配置GlobalConfig gc = new GlobalConfig();gc.setOutputDir(OUTPUT_DIR); // 输出目录gc.setAuthor(AUTHOR); // 作者gc.setOpen(false); // 是否打开输出目录gc.setSwagger2(true); // 实体属性 Swagger2 注解gc.setMapperName("%sMapper"); // mapper 名称gc.setXmlName("%sMapper"); // mapper xml 名称gc.setServiceName("%sService"); // service 名称gc.setServiceImplName("%sServiceImpl"); // service 实现类名称gc.setControllerName("%sController"); // controller 名称gc.setEntityName("%sEntity"); // entity 名称mpg.setGlobalConfig(gc);// 数据源配置DataSourceConfig dsc = new DataSourceConfig();dsc.setUrl(URL);dsc.setDriverName(DRIVER_NAME);dsc.setUsername(USERNAME);dsc.setPassword(PASSWORD);mpg.setDataSource(dsc);// 包配置PackageConfig pc = new PackageConfig();pc.setParent(PARENT); // 父包名pc.setModuleName(MODULE_NAME); // 模块名pc.setService("service");pc.setServiceImpl("service.impl");pc.setController("controller");pc.setEntity("entity");mpg.setPackageInfo(pc);// 自定义配置
//        InjectionConfig cfg = new InjectionConfig() {
//            @Override
//            public void initMap() {
//                // to do nothing
//            }
//        };// 模板引擎
//        String templatePath = "/templates/mapper.xml.vm";
//        // 自定义输出配置
//        List<FileOutConfig> focList = new ArrayList<>();
//        // 自定义 Mapper XML 路径
//        focList.add(new FileOutConfig(templatePath) {
//            @Override
//            public String outputFile(TableInfo tableInfo) {
//                return System.getProperty("user.dir") + "\\src\\main\\resources\\mapper\\" + MODULE_NAME
//                        + FileSystems.getDefault().getSeparator() + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
//            }
//        });
//        cfg.setFileOutConfigList(focList);
//        mpg.setCfg(cfg);// 配置模板TemplateConfig templateConfig = new TemplateConfig();templateConfig.setController("/templates/controller.java.vm");templateConfig.setEntity("/templates/entity.java.vm");templateConfig.setMapper("/templates/mapper.java.vm");templateConfig.setService("/templates/service.java.vm");templateConfig.setServiceImpl("/templates/serviceImpl.java.vm");templateConfig.setXml("/templates/mapper.xml.vm");mpg.setTemplate(templateConfig);// 策略配置StrategyConfig strategy = new StrategyConfig();strategy.setNaming(NamingStrategy.underline_to_camel); // 表名下划线转驼峰strategy.setColumnNaming(NamingStrategy.underline_to_camel); // 列名下划线转驼峰strategy.setEntityLombokModel(true); // 实体类使用 Lombokstrategy.setRestControllerStyle(true); // RestController 风格控制器strategy.setInclude(TABLE_NAME); // 需要生成的表名,多个表名传数组mpg.setStrategy(strategy);// 执行生成mpg.execute();System.out.println("--------------------> 代码生成完成");}
}

mybatis引擎模板

可以去GitHub的mybatis-plus代码库直接下载或者复制下来,但是考虑到不太方便,可以直接复制我的

注意了:工具类代码中的模板路径,例如:/templates/controller.java.vm 是在resources文件夹下templates文件中的。

controller.java.vm

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;
#end
#if(${superControllerClassPackage})
import ${superControllerClassPackage};
#end/*** <p>* $!{table.comment} 前端控制器* </p>** @author ${author}* @since ${date}*/
#if(${restControllerStyle})
@RestController
#else
@Controller
#end
@RequestMapping("#if(${package.ModuleName})/${package.ModuleName}#end/#if(${controllerMappingHyphenStyle})${controllerMappingHyphen}#else${table.entityPath}#end")
#if(${kotlin})
class ${table.controllerName}#if(${superControllerClass}) : ${superControllerClass}()#end#else#if(${superControllerClass})public class ${table.controllerName} extends ${superControllerClass} {#elsepublic class ${table.controllerName} {#end}
#end

entity.java.vm

package ${package.Entity};#foreach($pkg in ${table.importPackages})
import ${pkg};
#end
#if(${springdoc})
import io.swagger.v3.oas.annotations.media.Schema;
#elseif(${swagger})
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
#end
#if(${entityLombokModel})
import lombok.Getter;
import lombok.Setter;#if(${chainModel})import lombok.experimental.Accessors;#end
#end/*** <p>* $!{table.comment}* </p>** @author ${author}* @since ${date}*/
#if(${entityLombokModel})
@Getter
@Setter#if(${chainModel})@Accessors(chain = true)#end
#end
#if(${table.convert})
@TableName("${schemaName}${table.name}")
#end
#if(${springdoc})
@Schema(name = "${entity}", description = "$!{table.comment}")
#elseif(${swagger})
@ApiModel(value = "${entity}对象", description = "$!{table.comment}")
#end
#if(${superEntityClass})
public class ${entity} extends ${superEntityClass}#if(${activeRecord})<${entity}>#end {
#elseif(${activeRecord})public class ${entity} extends Model<${entity}> {
#elseif(${entitySerialVersionUID})public class ${entity} implements Serializable {
#elsepublic class ${entity} {
#end
#if(${entitySerialVersionUID})private static final long serialVersionUID = 1L;
#end
## ----------  BEGIN 字段循环遍历  ----------
#foreach($field in ${table.fields})#if(${field.keyFlag})#set($keyPropertyName=${field.propertyName})#end#if("$!field.comment" != "")#if(${springdoc})@Schema(description = "${field.comment}")#elseif(${swagger})@ApiModelProperty("${field.comment}")#else/*** ${field.comment}*/#end#end#if(${field.keyFlag})## 主键#if(${field.keyIdentityFlag})@TableId(value = "${field.annotationColumnName}", type = IdType.AUTO)#elseif(!$null.isNull(${idType}) && "$!idType" != "")@TableId(value = "${field.annotationColumnName}", type = IdType.${idType})#elseif(${field.convert})@TableId("${field.annotationColumnName}")#end## 普通字段#elseif(${field.fill})## -----   存在字段填充设置   -----#if(${field.convert})@TableField(value = "${field.annotationColumnName}", fill = FieldFill.${field.fill})#else@TableField(fill = FieldFill.${field.fill})#end#elseif(${field.convert})@TableField("${field.annotationColumnName}")#end## 乐观锁注解#if(${field.versionField})@Version#end## 逻辑删除注解#if(${field.logicDeleteField})@TableLogic#end
private ${field.propertyType} ${field.propertyName};
#end
## ----------  END 字段循环遍历  ----------
#if(!${entityLombokModel})#foreach($field in ${table.fields})#if(${field.propertyType.equals("boolean")})#set($getprefix="is")#else#set($getprefix="get")#endpublic ${field.propertyType} ${getprefix}${field.capitalName}() {return ${field.propertyName};}#if(${chainModel})public ${entity} set${field.capitalName}(${field.propertyType} ${field.propertyName}) {#elsepublic void set${field.capitalName}(${field.propertyType} ${field.propertyName}) {#endthis.${field.propertyName} = ${field.propertyName};#if(${chainModel})return this;#end}#end## --foreach end---
#end
## --end of #if(!${entityLombokModel})--
#if(${entityColumnConstant})#foreach($field in ${table.fields})public static final String ${field.name.toUpperCase()} = "${field.name}";#end
#end
#if(${activeRecord})@Overridepublic Serializable pkVal() {#if(${keyPropertyName})return this.${keyPropertyName};#elsereturn null;#end
}
#end
#if(!${entityLombokModel})@Overridepublic String toString() {return "${entity}{" +#foreach($field in ${table.fields})#if($!{foreach.index}==0)"${field.propertyName} = " + ${field.propertyName} +#else", ${field.propertyName} = " + ${field.propertyName} +#end#end"}";
}
#end
}

mapper.java.vm

package ${package.Mapper};import ${package.Entity}.${entity};
import ${superMapperClassPackage};
#if(${mapperAnnotationClass})
import ${mapperAnnotationClass.name};
#end/*** <p>* $!{table.comment} Mapper 接口* </p>** @author ${author}* @since ${date}*/
#if(${mapperAnnotationClass})
@${mapperAnnotationClass.simpleName}
#end
#if(${kotlin})
interface ${table.mapperName} : ${superMapperClass}<${entity}>
#else
public interface ${table.mapperName} extends ${superMapperClass}<${entity}> {}
#end

mapper.xml.vm

<?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#if(${baseColumnList})<!-- 通用查询结果列 --><sql id="Base_Column_List">
#foreach($field in ${table.commonFields})${field.name},
#end${table.fieldNames}</sql>#end
</mapper>

service.java.vm

package ${package.Service};import ${package.Entity}.${entity};
import ${superServiceClassPackage};/*** @Author: ${author}* @Date: ${cfg.dateTime}* @Description: $!{table.comment}服务类*/#if(${kotlin})
interface ${table.serviceName} : ${superServiceClass}<${entity}>
#else
public interface ${table.serviceName} extends ${superServiceClass}<${entity}> {}
#end

serviceImpl.java.vm

package ${package.ServiceImpl};import ${package.Entity}.${entity};
import ${package.Mapper}.${table.mapperName};
import ${package.Service}.${table.serviceName};
import ${superServiceImplClassPackage};
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;/*** @Author: ${author}* @Date: ${cfg.dateTime}* @Description: $!{table.comment}服务实现类*/
@Service
#if(${kotlin})
open class ${table.serviceImplName} : ${superServiceImplClass}<${table.mapperName}, ${entity}Model>(), ${table.serviceName} {}
#else
public class ${table.serviceImplName} extends ${superServiceImplClass}<${table.mapperName}, ${entity}> implements ${table.serviceName} {}
#end

这篇关于mybatis-plus代码生成器【一看就会,复制即用】的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1011217

相关文章

MyBatis-Plus 中 nested() 与 and() 方法详解(最佳实践场景)

《MyBatis-Plus中nested()与and()方法详解(最佳实践场景)》在MyBatis-Plus的条件构造器中,nested()和and()都是用于构建复杂查询条件的关键方法,但... 目录MyBATis-Plus 中nested()与and()方法详解一、核心区别对比二、方法详解1.and()

Conda虚拟环境的复制和迁移的四种方法实现

《Conda虚拟环境的复制和迁移的四种方法实现》本文主要介绍了Conda虚拟环境的复制和迁移的四种方法实现,包括requirements.txt,environment.yml,conda-pack,... 目录在本机复制Conda虚拟环境相同操作系统之间复制环境方法一:requirements.txt方法

MyBatis ResultMap 的基本用法示例详解

《MyBatisResultMap的基本用法示例详解》在MyBatis中,resultMap用于定义数据库查询结果到Java对象属性的映射关系,本文给大家介绍MyBatisResultMap的基本... 目录MyBATis 中的 resultMap1. resultMap 的基本语法2. 简单的 resul

Mybatis的分页实现方式

《Mybatis的分页实现方式》MyBatis的分页实现方式主要有以下几种,每种方式适用于不同的场景,且在性能、灵活性和代码侵入性上有所差异,对Mybatis的分页实现方式感兴趣的朋友一起看看吧... 目录​1. 原生 SQL 分页(物理分页)​​2. RowBounds 分页(逻辑分页)​​3. Page

MyBatis Plus 中 update_time 字段自动填充失效的原因分析及解决方案(最新整理)

《MyBatisPlus中update_time字段自动填充失效的原因分析及解决方案(最新整理)》在使用MyBatisPlus时,通常我们会在数据库表中设置create_time和update... 目录前言一、问题现象二、原因分析三、总结:常见原因与解决方法对照表四、推荐写法前言在使用 MyBATis

Mybatis Plus Join使用方法示例详解

《MybatisPlusJoin使用方法示例详解》:本文主要介绍MybatisPlusJoin使用方法示例详解,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,... 目录1、pom文件2、yaml配置文件3、分页插件4、示例代码:5、测试代码6、和PageHelper结合6

MyBatis设计SQL返回布尔值(Boolean)的常见方法

《MyBatis设计SQL返回布尔值(Boolean)的常见方法》这篇文章主要为大家详细介绍了MyBatis设计SQL返回布尔值(Boolean)的几种常见方法,文中的示例代码讲解详细,感兴趣的小伙伴... 目录方案一:使用COUNT查询存在性(推荐)方案二:条件表达式直接返回布尔方案三:存在性检查(EXI

Linux使用scp进行远程目录文件复制的详细步骤和示例

《Linux使用scp进行远程目录文件复制的详细步骤和示例》在Linux系统中,scp(安全复制协议)是一个使用SSH(安全外壳协议)进行文件和目录安全传输的命令,它允许在远程主机之间复制文件和目录,... 目录1. 什么是scp?2. 语法3. 示例示例 1: 复制本地目录到远程主机示例 2: 复制远程主

Mysql的主从同步/复制的原理分析

《Mysql的主从同步/复制的原理分析》:本文主要介绍Mysql的主从同步/复制的原理分析,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录为什么要主从同步?mysql主从同步架构有哪些?Mysql主从复制的原理/整体流程级联复制架构为什么好?Mysql主从复制注意

Python实现自动化Word文档样式复制与内容生成

《Python实现自动化Word文档样式复制与内容生成》在办公自动化领域,高效处理Word文档的样式和内容复制是一个常见需求,本文将展示如何利用Python的python-docx库实现... 目录一、为什么需要自动化 Word 文档处理二、核心功能实现:样式与表格的深度复制1. 表格复制(含样式与内容)2