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

相关文章

Python虚拟环境终极(含PyCharm的使用教程)

《Python虚拟环境终极(含PyCharm的使用教程)》:本文主要介绍Python虚拟环境终极(含PyCharm的使用教程),具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,... 目录一、为什么需要虚拟环境?二、虚拟环境创建方式对比三、命令行创建虚拟环境(venv)3.1 基础命令3

Python Transformer 库安装配置及使用方法

《PythonTransformer库安装配置及使用方法》HuggingFaceTransformers是自然语言处理(NLP)领域最流行的开源库之一,支持基于Transformer架构的预训练模... 目录python 中的 Transformer 库及使用方法一、库的概述二、安装与配置三、基础使用:Pi

关于pandas的read_csv方法使用解读

《关于pandas的read_csv方法使用解读》:本文主要介绍关于pandas的read_csv方法使用,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录pandas的read_csv方法解读read_csv中的参数基本参数通用解析参数空值处理相关参数时间处理相关

使用Node.js制作图片上传服务的详细教程

《使用Node.js制作图片上传服务的详细教程》在现代Web应用开发中,图片上传是一项常见且重要的功能,借助Node.js强大的生态系统,我们可以轻松搭建高效的图片上传服务,本文将深入探讨如何使用No... 目录准备工作搭建 Express 服务器配置 multer 进行图片上传处理图片上传请求完整代码示例

SpringBoot条件注解核心作用与使用场景详解

《SpringBoot条件注解核心作用与使用场景详解》SpringBoot的条件注解为开发者提供了强大的动态配置能力,理解其原理和适用场景是构建灵活、可扩展应用的关键,本文将系统梳理所有常用的条件注... 目录引言一、条件注解的核心机制二、SpringBoot内置条件注解详解1、@ConditionalOn

Python中使用正则表达式精准匹配IP地址的案例

《Python中使用正则表达式精准匹配IP地址的案例》Python的正则表达式(re模块)是完成这个任务的利器,但你知道怎么写才能准确匹配各种合法的IP地址吗,今天我们就来详细探讨这个问题,感兴趣的朋... 目录为什么需要IP正则表达式?IP地址的基本结构基础正则表达式写法精确匹配0-255的数字验证IP地

使用Python实现全能手机虚拟键盘的示例代码

《使用Python实现全能手机虚拟键盘的示例代码》在数字化办公时代,你是否遇到过这样的场景:会议室投影电脑突然键盘失灵、躺在沙发上想远程控制书房电脑、或者需要给长辈远程协助操作?今天我要分享的Pyth... 目录一、项目概述:不止于键盘的远程控制方案1.1 创新价值1.2 技术栈全景二、需求实现步骤一、需求

Spring LDAP目录服务的使用示例

《SpringLDAP目录服务的使用示例》本文主要介绍了SpringLDAP目录服务的使用示例... 目录引言一、Spring LDAP基础二、LdapTemplate详解三、LDAP对象映射四、基本LDAP操作4.1 查询操作4.2 添加操作4.3 修改操作4.4 删除操作五、认证与授权六、高级特性与最佳

Java中Date、LocalDate、LocalDateTime、LocalTime、时间戳之间的相互转换代码

《Java中Date、LocalDate、LocalDateTime、LocalTime、时间戳之间的相互转换代码》:本文主要介绍Java中日期时间转换的多种方法,包括将Date转换为LocalD... 目录一、Date转LocalDateTime二、Date转LocalDate三、LocalDateTim

MySQL中动态生成SQL语句去掉所有字段的空格的操作方法

《MySQL中动态生成SQL语句去掉所有字段的空格的操作方法》在数据库管理过程中,我们常常会遇到需要对表中字段进行清洗和整理的情况,本文将详细介绍如何在MySQL中动态生成SQL语句来去掉所有字段的空... 目录在mysql中动态生成SQL语句去掉所有字段的空格准备工作原理分析动态生成SQL语句在MySQL