mybatis-plus-generator 使用 velocity 生成前后台代码

2024-03-13 03:04

本文主要是介绍mybatis-plus-generator 使用 velocity 生成前后台代码,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

操作步骤

        1)准备mybatis-plus 生成代码的 vm文件

        2)添加依赖 mybatis-plus-generator 代码生成器的依赖

        3)执行工具方法生成代码

1、准备 mybatis-plus 生成代码的 vm文件

1)找vm模板

去工程的 external Libraries 找到 mybatisplus-generator 下 的vm 模版

2)根据模板编写模版代码

如下图,包含所有前后台代码、菜单sql;代码结构仿照若依,基础模版来自mybatisplus-generator

提供基础的基本包含所的 :entity.java.vm ,包含数据库必字段判断的生成规则

package ${package.Entity};import com.alibaba.excel.annotation.ExcelIgnore;
import com.alibaba.excel.annotation.ExcelProperty;
#foreach($pkg in $table.importPackages)
#if(!$reTool.contains("(io\.Serializable)",$pkg))
import ${pkg};
#end
#end
#if($swagger)
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
#end
import jakarta.validation.constraints.NotNull;
#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($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 {
#else
public class ${entity} {
#end
#*#if($entitySerialVersionUID)private static final long serialVersionUID = 1L;
#end*#
#*-- ----------  BEGIN 字段循环遍历  ----------*#
#foreach($field in $table.fields)#if($tool.isNotEmpty($field.comment))#if($swagger)@ApiModelProperty("${field.comment}")#else/*** ${field.comment}*/#end#end#if($field.keyFlag)#if($field.keyIdentityFlag)@TableId(value = "${field.annotationColumnName}", type = IdType.AUTO)#elseif($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#if(!$field.keyFlag && $field.metaInfo && !$field.metaInfo.nullable)@NotNull(message = "${field.comment} 不应为空")#*不验证主键和二进制类型 为空*##end#if($field.keyFlag || $field.propertyType == "byte[]")@ExcelIgnore#*-- 主键或二进制不导入 --*##end@ExcelProperty("#if($field.metaInfo && !$field.metaInfo.nullable)*#end${field.comment}")private ${field.propertyType} ${field.propertyName};#end
#*------------  END 字段循环遍历  ----------*#
#if(!$entityLombokModel)
#foreach($field in $table.fields)#if($field.propertyType == "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
#end
#if(!$entityLombokModel)@Overridepublic String toString() {return "${entity}{" +#foreach($field in $table.fields)#if($field_index == 0)"${field.propertyName}=" + ${field.propertyName} +#else", ${field.propertyName}=" + ${field.propertyName} +#end#end"}";}
#end
}

2、添加依赖 mybatis-plus-generator 代码生成器的依赖 

<!-- MySQL Connector --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.33</version></dependency><!-- MyBatis Plus --><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.5.5</version></dependency><!-- Code Generator --><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-generator</artifactId><version>3.5.5</version></dependency><!--velocity代码生成使用模板 --><dependency><groupId>org.apache.velocity</groupId><artifactId>velocity-engine-core</artifactId><version>2.3</version></dependency><dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>5.8.25</version></dependency><dependency><groupId>org.jetbrains</groupId><artifactId>annotations</artifactId><version>16.0.3</version><scope>compile</scope></dependency>

3、编写生成器代码 3个 类

入口: AutoGeneratorUtils ;
自定义文件名:DefVelocityTemplateEngine ;
所有 Entity的父类:CommonEntity (名字感觉不是太直观)

1)入口: AutoGeneratorUtils ,编写完直接运行

package com.demo;import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.generator.config.builder.CustomFile;import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.demo.common.pojo.CommonEntity;
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.OutputFile;import java.util.Collections;
import java.util.HashMap;
import java.util.Map;/*** IDaaS后台管理系统代码生成工具* 代码生成器,基于mybatis-plus-generator,需要引入以下两个依赖* implementation("com.baomidou:mybatis-plus-generator:3.5.2")* implementation("org.freemarker:freemarker:2.3.32")*/
public class AutoGeneratorUtils {/*** 指定模块名**/private static String MODULE_NAME = "sys";/*** 指定表明**/private static String TABLE_NAME = "sys_logininfor";/*** 你的所属上级菜单 ID**/private static String PARENT_MENU_ID = "b648b666-9af5-4bfa-8036-7d09f3439c2c";/*** 过滤表前缀**/private static String[] TABLE_PREFIX = {"buz_", "t_", "c_"};/*** 作者**/private static String AUTHOR = "admin";/*** 数据源信息*/private static String JDBC_URL = "jdbc:mysql://localhost:3306/ry-vue?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8";private static String USER_NAME = "root";private static String PASSWORD = "123456";/*** 包设置*/private static String PARENT = "com.ruoyi.web";private static String MAPPER_XML_PATH = "/resources/mapper";private static String VUE_PATH = "/vue/views/";private static String VUE_JS_PATH = "/vue/api";private static String MENU_SQL_PATH = "/sql";/*** 代码输出路径*/private static String OUTPUT_DIR = "D://temp";public static void main(String[] args) {String entityPath = getEntityPath();FastAutoGenerator.create(JDBC_URL, USER_NAME, PASSWORD)// 全局配置.globalConfig(builder -> {builder.author(AUTHOR) // 设置作者//.enableSwagger() // 开启 swagger 模式.dateType(DateType.ONLY_DATE) //设置全局的时间类型为 Date.outputDir(OUTPUT_DIR); // 指定输出目录})// 包配置.packageConfig(builder -> {builder.parent(PARENT) // 设置父包名.moduleName(MODULE_NAME) // 设置父包模块名.pathInfo(Collections.singletonMap(OutputFile.xml, OUTPUT_DIR + MAPPER_XML_PATH)); // 设置mapperXml生成路径})// 策略配置.strategyConfig(builder -> {builder.addInclude(TABLE_NAME) // 设置需要生成的表名.addTablePrefix(TABLE_PREFIX) // 设置过滤表前缀// 实体策略配置.entityBuilder().superClass(CommonEntity.class) //设置所有实体类的父类.enableLombok() //启用lombok get set// Controller策略配置.controllerBuilder().enableFileOverride() // 覆盖已生成文件.enableRestStyle(); //开启生成@RestController 控制器}).templateEngine(new DefVelocityTemplateEngine())// 使用默认的是 VelocityTemplateEngine 引擎模板,也可以是 FreemarkerTemplateEngine// 模板配置.templateConfig(builder -> {builder.entity("/templates/java/entity.java.vm").service("/templates/java/service.java.vm").serviceImpl("/templates/java/serviceImpl.java.vm").mapper("/templates/java/mapper.java.vm").xml("/templates/xml/mapper.xml.vm").controller("/templates/java/controller.java.vm");}).injectionConfig(consumer -> {// voconsumer.customFile(new CustomFile.Builder().fileName("Param.java").packageName("entity.vo").templatePath("/templates/java/entityParam.java.vm").build());// 前端consumer.customFile(new CustomFile.Builder().fileName("Index.vue").filePath(OUTPUT_DIR + VUE_PATH + "/" + MODULE_NAME + "/" + entityPath).templatePath("/templates/vue/Index.vue.vm").build());consumer.customFile(new CustomFile.Builder().fileName("Form.vue").filePath(OUTPUT_DIR + VUE_PATH + "/" + MODULE_NAME + "/" + entityPath).templatePath("/templates/vue/Form.vue.vm").build());consumer.customFile(new CustomFile.Builder().fileName("Import.vue").filePath(OUTPUT_DIR + VUE_PATH + "/" + MODULE_NAME + "/" + entityPath).templatePath("/templates/vue/Import.vue.vm").build());consumer.customFile(new CustomFile.Builder().fileName(".js").filePath(OUTPUT_DIR + VUE_JS_PATH + "/" + MODULE_NAME).templatePath("/templates/js/api.js.vm").build());consumer.customFile(new CustomFile.Builder().fileName(".sql").filePath(OUTPUT_DIR + MENU_SQL_PATH).templatePath("/templates/sql/sql.vm").build());//添加自定义工具类,主要用 tool.lowerFirst(字符)、upperFirst(字符)、isEmpty(字符)、isNotEmpty(字符)、subBefore(字符串,分隔符,true)Map<String, Object> toolMap = new HashMap<>();toolMap.put("tool", new StrUtil());//json工具,方便判断对象中存在的属性 jsonTool.toJsonStr(对象)toolMap.put("jsonTool", new JSONUtil());//正则表达式工具,方便剔除不用的类 reTool.isMatch(正则表达式,内容),reTool.contains(正则表达式,内容)toolMap.put("reTool", new ReUtil());//添加自定义变量toolMap.put("parentMenuId", PARENT_MENU_ID);consumer.customMap(toolMap);}).execute();}public static String getEntityPath() {String entityPath = ObjectUtil.clone(TABLE_NAME);if (ArrayUtil.isNotEmpty(TABLE_PREFIX)) {for (int i = 0; i < TABLE_PREFIX.length; i++) {entityPath = StrUtil.removeAll(entityPath, TABLE_PREFIX[i]);}}//转换驼峰规则entityPath = StrUtil.toCamelCase(entityPath);//首字母小写return StrUtil.lowerFirst(entityPath);}
}

2)自定义文件名:DefVelocityTemplateEngine ;

package com.demo;import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.config.builder.CustomFile;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.engine.VelocityTemplateEngine;
import org.jetbrains.annotations.NotNull;import java.io.File;
import java.util.List;
import java.util.Map;public class DefVelocityTemplateEngine extends VelocityTemplateEngine {@Overrideprotected void outputCustomFile(@NotNull List<CustomFile> customFiles, @NotNull TableInfo tableInfo, @NotNull Map<String, Object> objectMap) {String entityName = tableInfo.getEntityName();String firstLowerEntityName = StrUtil.lowerFirst(entityName);String parentPath = this.getPathInfo(OutputFile.parent);customFiles.forEach((file) -> {String filePath = StrUtil.isNotBlank(file.getFilePath()) ? file.getFilePath() : parentPath;if (StrUtil.isNotBlank(file.getPackageName())) {filePath = filePath + File.separator + file.getPackageName();filePath = filePath.replaceAll("\\.", "\\" + File.separator);}String fileName = StrUtil.nullToEmpty(file.getFileName());fileName = filePath + File.separator + (ReUtil.isMatch(".*\\.(js|vue)$", fileName) ? firstLowerEntityName : entityName) + fileName;this.outputFile(new File(fileName), objectMap, file.getTemplatePath(), file.isFileOverride());});}
}

3)所有 Entity的父类:CommonEntity

仅做演示啥都没有

package com.demo.common.pojo;public class CommonEntity {
}

4、运行效果

其中导入导出逻辑采用easyexcel:参考文档

easyExcel 导入、导出Excel 封装公共的方法-CSDN博客文章浏览阅读84次,点赞4次,收藏2次。*** 导出采购订单列表*/@Log(title = "采购订单", businessType = BusinessType.EXPORT)List listDatas = 获取数据的service方法nmwDate.setFileName("历史生产数据");https://blog.csdn.net/qq_26408545/article/details/136654488

这篇关于mybatis-plus-generator 使用 velocity 生成前后台代码的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

使用Go语言开发一个命令行文件管理工具

《使用Go语言开发一个命令行文件管理工具》这篇文章主要为大家详细介绍了如何使用Go语言开发一款命令行文件管理工具,支持批量重命名,删除,创建,移动文件,需要的小伙伴可以了解下... 目录一、工具功能一览二、核心代码解析1. 主程序结构2. 批量重命名3. 批量删除4. 创建文件/目录5. 批量移动三、如何安

springboot的调度服务与异步服务使用详解

《springboot的调度服务与异步服务使用详解》本文主要介绍了Java的ScheduledExecutorService接口和SpringBoot中如何使用调度线程池,包括核心参数、创建方式、自定... 目录1.调度服务1.1.JDK之ScheduledExecutorService1.2.spring

Java使用Tesseract-OCR实战教程

《Java使用Tesseract-OCR实战教程》本文介绍了如何在Java中使用Tesseract-OCR进行文本提取,包括Tesseract-OCR的安装、中文训练库的配置、依赖库的引入以及具体的代... 目录Java使用Tesseract-OCRTesseract-OCR安装配置中文训练库引入依赖代码实

Python使用Pandas对比两列数据取最大值的五种方法

《Python使用Pandas对比两列数据取最大值的五种方法》本文主要介绍使用Pandas对比两列数据取最大值的五种方法,包括使用max方法、apply方法结合lambda函数、函数、clip方法、w... 目录引言一、使用max方法二、使用apply方法结合lambda函数三、使用np.maximum函数

Qt 中集成mqtt协议的使用方法

《Qt中集成mqtt协议的使用方法》文章介绍了如何在工程中引入qmqtt库,并通过声明一个单例类来暴露订阅到的主题数据,本文通过实例代码给大家介绍的非常详细,感兴趣的朋友一起看看吧... 目录一,引入qmqtt 库二,使用一,引入qmqtt 库我是将整个头文件/源文件都添加到了工程中进行编译,这样 跨平台

C++使用栈实现括号匹配的代码详解

《C++使用栈实现括号匹配的代码详解》在编程中,括号匹配是一个常见问题,尤其是在处理数学表达式、编译器解析等任务时,栈是一种非常适合处理此类问题的数据结构,能够精确地管理括号的匹配问题,本文将通过C+... 目录引言问题描述代码讲解代码解析栈的状态表示测试总结引言在编程中,括号匹配是一个常见问题,尤其是在

Java中String字符串使用避坑指南

《Java中String字符串使用避坑指南》Java中的String字符串是我们日常编程中用得最多的类之一,看似简单的String使用,却隐藏着不少“坑”,如果不注意,可能会导致性能问题、意外的错误容... 目录8个避坑点如下:1. 字符串的不可变性:每次修改都创建新对象2. 使用 == 比较字符串,陷阱满

Python使用国内镜像加速pip安装的方法讲解

《Python使用国内镜像加速pip安装的方法讲解》在Python开发中,pip是一个非常重要的工具,用于安装和管理Python的第三方库,然而,在国内使用pip安装依赖时,往往会因为网络问题而导致速... 目录一、pip 工具简介1. 什么是 pip?2. 什么是 -i 参数?二、国内镜像源的选择三、如何

使用C++实现链表元素的反转

《使用C++实现链表元素的反转》反转链表是链表操作中一个经典的问题,也是面试中常见的考题,本文将从思路到实现一步步地讲解如何实现链表的反转,帮助初学者理解这一操作,我们将使用C++代码演示具体实现,同... 目录问题定义思路分析代码实现带头节点的链表代码讲解其他实现方式时间和空间复杂度分析总结问题定义给定

Linux使用nload监控网络流量的方法

《Linux使用nload监控网络流量的方法》Linux中的nload命令是一个用于实时监控网络流量的工具,它提供了传入和传出流量的可视化表示,帮助用户一目了然地了解网络活动,本文给大家介绍了Linu... 目录简介安装示例用法基础用法指定网络接口限制显示特定流量类型指定刷新率设置流量速率的显示单位监控多个