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使用FastAPI实现大文件分片上传与断点续传功能

《Python使用FastAPI实现大文件分片上传与断点续传功能》大文件直传常遇到超时、网络抖动失败、失败后只能重传的问题,分片上传+断点续传可以把大文件拆成若干小块逐个上传,并在中断后从已完成分片继... 目录一、接口设计二、服务端实现(FastAPI)2.1 运行环境2.2 目录结构建议2.3 serv

C#实现千万数据秒级导入的代码

《C#实现千万数据秒级导入的代码》在实际开发中excel导入很常见,现代社会中很容易遇到大数据处理业务,所以本文我就给大家分享一下千万数据秒级导入怎么实现,文中有详细的代码示例供大家参考,需要的朋友可... 目录前言一、数据存储二、处理逻辑优化前代码处理逻辑优化后的代码总结前言在实际开发中excel导入很

MyBatis分页查询实战案例完整流程

《MyBatis分页查询实战案例完整流程》MyBatis是一个强大的Java持久层框架,支持自定义SQL和高级映射,本案例以员工工资信息管理为例,详细讲解如何在IDEA中使用MyBatis结合Page... 目录1. MyBATis框架简介2. 分页查询原理与应用场景2.1 分页查询的基本原理2.1.1 分

Spring Security简介、使用与最佳实践

《SpringSecurity简介、使用与最佳实践》SpringSecurity是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架,本文给大家介绍SpringSec... 目录一、如何理解 Spring Security?—— 核心思想二、如何在 Java 项目中使用?——

SpringBoot+RustFS 实现文件切片极速上传的实例代码

《SpringBoot+RustFS实现文件切片极速上传的实例代码》本文介绍利用SpringBoot和RustFS构建高性能文件切片上传系统,实现大文件秒传、断点续传和分片上传等功能,具有一定的参考... 目录一、为什么选择 RustFS + SpringBoot?二、环境准备与部署2.1 安装 RustF

springboot中使用okhttp3的小结

《springboot中使用okhttp3的小结》OkHttp3是一个JavaHTTP客户端,可以处理各种请求类型,比如GET、POST、PUT等,并且支持高效的HTTP连接池、请求和响应缓存、以及异... 在 Spring Boot 项目中使用 OkHttp3 进行 HTTP 请求是一个高效且流行的方式。

MyBatis Plus实现时间字段自动填充的完整方案

《MyBatisPlus实现时间字段自动填充的完整方案》在日常开发中,我们经常需要记录数据的创建时间和更新时间,传统的做法是在每次插入或更新操作时手动设置这些时间字段,这种方式不仅繁琐,还容易遗漏,... 目录前言解决目标技术栈实现步骤1. 实体类注解配置2. 创建元数据处理器3. 服务层代码优化填充机制详

Python实现Excel批量样式修改器(附完整代码)

《Python实现Excel批量样式修改器(附完整代码)》这篇文章主要为大家详细介绍了如何使用Python实现一个Excel批量样式修改器,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一... 目录前言功能特性核心功能界面特性系统要求安装说明使用指南基本操作流程高级功能技术实现核心技术栈关键函

mybatis映射器配置小结

《mybatis映射器配置小结》本文详解MyBatis映射器配置,重点讲解字段映射的三种解决方案(别名、自动驼峰映射、resultMap),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定... 目录select中字段的映射问题使用SQL语句中的别名功能使用mapUnderscoreToCame

Java使用Javassist动态生成HelloWorld类

《Java使用Javassist动态生成HelloWorld类》Javassist是一个非常强大的字节码操作和定义库,它允许开发者在运行时创建新的类或者修改现有的类,本文将简单介绍如何使用Javass... 目录1. Javassist简介2. 环境准备3. 动态生成HelloWorld类3.1 创建CtC