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实现IP地址和端口状态检测与监控

《使用Python实现IP地址和端口状态检测与监控》在网络运维和服务器管理中,IP地址和端口的可用性监控是保障业务连续性的基础需求,本文将带你用Python从零打造一个高可用IP监控系统,感兴趣的小伙... 目录概述:为什么需要IP监控系统使用步骤说明1. 环境准备2. 系统部署3. 核心功能配置系统效果展

使用Java将各种数据写入Excel表格的操作示例

《使用Java将各种数据写入Excel表格的操作示例》在数据处理与管理领域,Excel凭借其强大的功能和广泛的应用,成为了数据存储与展示的重要工具,在Java开发过程中,常常需要将不同类型的数据,本文... 目录前言安装免费Java库1. 写入文本、或数值到 Excel单元格2. 写入数组到 Excel表格

redis中使用lua脚本的原理与基本使用详解

《redis中使用lua脚本的原理与基本使用详解》在Redis中使用Lua脚本可以实现原子性操作、减少网络开销以及提高执行效率,下面小编就来和大家详细介绍一下在redis中使用lua脚本的原理... 目录Redis 执行 Lua 脚本的原理基本使用方法使用EVAL命令执行 Lua 脚本使用EVALSHA命令

Java 中的 @SneakyThrows 注解使用方法(简化异常处理的利与弊)

《Java中的@SneakyThrows注解使用方法(简化异常处理的利与弊)》为了简化异常处理,Lombok提供了一个强大的注解@SneakyThrows,本文将详细介绍@SneakyThro... 目录1. @SneakyThrows 简介 1.1 什么是 Lombok?2. @SneakyThrows

MyBatis模糊查询报错:ParserException: not supported.pos 问题解决

《MyBatis模糊查询报错:ParserException:notsupported.pos问题解决》本文主要介绍了MyBatis模糊查询报错:ParserException:notsuppo... 目录问题描述问题根源错误SQL解析逻辑深层原因分析三种解决方案方案一:使用CONCAT函数(推荐)方案二:

使用Python和Pyecharts创建交互式地图

《使用Python和Pyecharts创建交互式地图》在数据可视化领域,创建交互式地图是一种强大的方式,可以使受众能够以引人入胜且信息丰富的方式探索地理数据,下面我们看看如何使用Python和Pyec... 目录简介Pyecharts 简介创建上海地图代码说明运行结果总结简介在数据可视化领域,创建交互式地

Java Stream流使用案例深入详解

《JavaStream流使用案例深入详解》:本文主要介绍JavaStream流使用案例详解,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录前言1. Lambda1.1 语法1.2 没参数只有一条语句或者多条语句1.3 一个参数只有一条语句或者多

Java Spring 中 @PostConstruct 注解使用原理及常见场景

《JavaSpring中@PostConstruct注解使用原理及常见场景》在JavaSpring中,@PostConstruct注解是一个非常实用的功能,它允许开发者在Spring容器完全初... 目录一、@PostConstruct 注解概述二、@PostConstruct 注解的基本使用2.1 基本代

C#使用StackExchange.Redis实现分布式锁的两种方式介绍

《C#使用StackExchange.Redis实现分布式锁的两种方式介绍》分布式锁在集群的架构中发挥着重要的作用,:本文主要介绍C#使用StackExchange.Redis实现分布式锁的... 目录自定义分布式锁获取锁释放锁自动续期StackExchange.Redis分布式锁获取锁释放锁自动续期分布式

springboot使用Scheduling实现动态增删启停定时任务教程

《springboot使用Scheduling实现动态增删启停定时任务教程》:本文主要介绍springboot使用Scheduling实现动态增删启停定时任务教程,具有很好的参考价值,希望对大家有... 目录1、配置定时任务需要的线程池2、创建ScheduledFuture的包装类3、注册定时任务,增加、删