本文主要是介绍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 生成前后台代码的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!