MybatisPlus代码生成器配置(处理blob等类型)

news2024/10/6 1:35:45

一:新建springboot项目

二:导包

<dependencies>
  <dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-generator</artifactId>
    <version>3.3.2</version>
  </dependency>
  <dependency>
    <groupId>org.apache.velocity</groupId>
    <artifactId>velocity-engine-core</artifactId>
    <version>2.2</version>
  </dependency>
  <dependency>
    <groupId>org.freemarker</groupId>
    <artifactId>freemarker</artifactId>
    <version>2.3.30</version>
  </dependency>
  <dependency>
    <groupId>com.ibeetl</groupId>
    <artifactId>beetl</artifactId>
    <version>3.1.8.RELEASE</version>
  </dependency>
  <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.20</version>
  </dependency>
  <dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-simple</artifactId>
    <version>1.7.25</version>
    <scope>compile</scope>
  </dependency>
</dependencies>

三:复制相应的模板到\resources\templates目录下

以下为模板链接

mybatis-plus/mybatis-plus-generator/src/main at 3.0 · baomidou/mybatis-plus · GitHub

 

 entity.java.vm文件如下

package ${package.Entity};

#foreach($pkg in ${table.importPackages})
import ${pkg};
#end
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
#if(${entityLombokModel})
import lombok.Data;
import lombok.EqualsAndHashCode;
##import lombok.experimental.Accessors;
#end

/**
 * @Description:$!{table.comment}
 * @author ${author}
 * @since ${date}
 */
@ApiModel(value ="$!{table.comment}")
#if(${entityLombokModel})
@Data
#if(${superEntityClass})
@EqualsAndHashCode(callSuper = true)
#else
@EqualsAndHashCode(callSuper = false)
#end
##@Accessors(chain = true)
#end
#if(${table.convert})
@TableName("${table.name}")
#end
#if(${superEntityClass})
public class ${entity} extends ${superEntityClass}#if(${activeRecord})<${entity}>#end {
#elseif(${activeRecord})
public class ${entity} extends Model<${entity}> {
#else
public class ${entity} implements Serializable {
#end

    private static final long serialVersionUID = 1L;

## ----------  BEGIN 字段循环遍历  ----------
#foreach($field in ${table.fields})
    #if(${field.keyFlag})
        #set($keyPropertyName=${field.propertyName})
    #end
    #if("$!field.comment" != "")
    @ApiModelProperty(value = "${field.comment}")
    #end
    #if(${field.keyFlag})
    ## 主键s
    #if(${field.keyIdentityFlag})
    @TableId(value = "${field.name}", type = IdType.AUTO)
    #elseif(!$null.isNull(${idType}) && "$!idType" != "")
    @TableId(value = "${field.name}", type = IdType.${idType})
    #elseif(${field.convert})
    @TableId("${field.name}")
    #end
    ## 普通字段
    #elseif(${field.fill})
    ## -----   存在字段填充设置   -----
        #if(${field.convert})
        @TableField(value = "${field.name}", fill = FieldFill.${field.fill})
        #else
        @TableField(fill = FieldFill.${field.fill})
        #end
    #elseif(${field.convert})
    @TableField("${field.name}")
    #else
    @TableField("${field.name}")
    #end
## 乐观锁注解
    #if(${versionFieldName}==${field.name})
    @Version
    #end
## 逻辑删除注解
    #if(${logicDeleteFieldName}==${field.name})
    @TableLogic
    #end
    private ${field.propertyType} ${field.propertyName};
#end
## ----------  END 字段循环遍历  ----------

#if(!${entityLombokModel})
    #foreach($field in ${table.fields})
        #if(${field.propertyType.equals("boolean")})
            #set($getprefix="is")
        #else
            #set($getprefix="get")
        #end

    public ${field.propertyType} ${getprefix}${field.capitalName}() {
            return ${field.propertyName};
            }

        #if(${entityBuilderModel})
        public ${entity} set${field.capitalName}(${field.propertyType} ${field.propertyName}) {
        #else
        public void set${field.capitalName}(${field.propertyType} ${field.propertyName}) {
        #end
            this.${field.propertyName} = ${field.propertyName};
        #if(${entityBuilderModel})
                return this;
        #end
        }
    #end
#end

#if(${entityColumnConstant})
    #foreach($field in ${table.fields})
    public static final String ${field.name.toUpperCase()} = "${field.name}";

    #end
#end
#if(${activeRecord})
    @Override
    protected Serializable pkVal() {
    #if(${keyPropertyName})
            return this.${keyPropertyName};
    #else
            return null;
    #end
    }
#end
#if(!${entityLombokModel})
    @Override
    public String toString() {
        return "${entity}{" +
    #foreach($field in ${table.fields})
        #if($!{velocityCount}==1)
                "${field.propertyName}=" + ${field.propertyName} +
        #else
                ", ${field.propertyName}=" + ${field.propertyName} +
        #end
    #end
        "}";
    }
#end
}

四:生成策略,main方法


import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class CodeGenerator {

    /**
     * <p>
     * 读取控制台内容
     * </p>
     */
    public static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        StringBuilder help = new StringBuilder();
        help.append("请输入" + tip + ":");
        System.out.println(help.toString());
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StringUtils.isNotEmpty(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("请输入正确的" + tip + "!");
    }

    public static void main(String[] args) {
        AutoGenerator mpg = new AutoGenerator();

        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        final String projectPath = System.getProperty("user.dir");
//        gc.setOutputDir(projectPath + "/src/main/java");//输出文件路径
        gc.setOutputDir(projectPath + "/idp-mybatis-plus-generator/codeGenerate");//输出文件路径
//        gc.setOutputDir(projectPath + "/pds-api/src/main/java");//输出文件路径
        gc.setFileOverride(true); // 是否文件覆盖
        gc.setActiveRecord(false);// 不需要ActiveRecord(实体类继承Model)特性的请改为false
        gc.setEnableCache(false);// XML 二级缓存
        gc.setBaseResultMap(true);// XML ResultMap
        gc.setBaseColumnList(true);// XML ColumnList
        gc.setEntityName("%s");
        gc.setAuthor("zz");// 作者

        // 自定义文件命名,注意 %s 会自动填充表实体属性!
        gc.setControllerName("%sController");
        // 默认service接口名IXXXService 自定义指定之后就不会用I开头了
        gc.setServiceName("%sService");
        gc.setServiceImplName("%sServiceImpl");
        gc.setMapperName("%sMapper");
        //gc.setXmlName("%sMapper");
        //设置日期格式,默认格式为 LocalDateTime 和 LocalDate
        gc.setDateType(DateType.ONLY_DATE);
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        // 自定义数据库表字段类型转换
        dsc.setTypeConvert((GlobalConfig gc2,String fieldType) -> {
            String t = fieldType;
            if (t.contains("char") || t.contains("text")) {
                return DbColumnType.STRING;
            } else if (t.contains("bigint")) {
                return DbColumnType.LONG;
            } else if (t.contains("int")) {
                return DbColumnType.INTEGER;
            } else if (t.contains("date") || t.contains("time") || t.contains("year")) {
                return DbColumnType.DATE;
            } else if (t.contains("text")) {
                return DbColumnType.STRING;
            } else if (t.contains("bit")) {
                return DbColumnType.BOOLEAN;
            } else if (t.contains("decimal")) {
                return DbColumnType.BIG_DECIMAL;
            } else if (t.contains("clob")) {
                return DbColumnType.STRING;
            } else if (t.contains("blob")) {
                return DbColumnType.STRING;
            } else if (t.contains("binary")) {
                return DbColumnType.BYTE_ARRAY;
            } else if (t.contains("float")) {
                return DbColumnType.FLOAT;
            } else if (t.contains("double")) {
                return DbColumnType.DOUBLE;
            } else if (t.contains("json") || t.contains("enum")) {
                return DbColumnType.STRING;
            }
            return DbColumnType.STRING;
        });
        dsc.setDbType(DbType.MYSQL);
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername("xxx");
        dsc.setPassword("xxx");
        dsc.setUrl("jdbc:mysql://127.0.0.1:3306/test?serverTimezone=UTC&characterEncoding=utf-8");
        mpg.setDataSource(dsc);

        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
            }
        };
        String templatePath = "/templates/mapper.xml.vm"; // Velocity模板
        // 自定义输出配置
        List<FileOutConfig> focList = new ArrayList<FileOutConfig>();
        // 自定义配置会被优先输出
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
                String result = projectPath + "/idp-mybatis-plus-generator/codeGenerate/resources/mappings/pds"
//                        + pc.getModuleName()
                        + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
                return result;
            }
        });
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        // 配置模板
        TemplateConfig tc = new TemplateConfig();
        // templates/entity.java 模板路径配置,默认在templates目录下,.vm 后缀不用加
        tc.setEntity("templates/entity.java");//使用自定义模板生成实体类
        tc.setXml("");
        mpg.setTemplate(tc);

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setEntityLombokModel(true);
        strategy.setEntitySerialVersionUID(true);
        strategy.setRestControllerStyle(true);
        //strategy.setTablePrefix(new String[]{"fac_"});// 此处可以修改为您的表前缀
        strategy.setNaming(NamingStrategy.underline_to_camel);// 表名生成策略(下划线转驼峰)
        strategy.setSuperControllerClass("com.hnac.hzsidp.pds.web.CommonController");
        //strategy.setSuperEntityClass(PrecBaseInfo.class);
        //strategy.setSuperEntityColumns("id", "create_user", "create_dept", "create_time", "update_user", "update_time", "status", "is_deleted");
        //strategy.setSuperEntityColumns("name", "info");
        strategy.setInclude("author_scope_api", "author_user"); // 需要生成的表名

        strategy.setSuperMapperClass(null);

        mpg.setStrategy(strategy);

        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setParent("com.hnac.hzsidp.pds");
        pc.setController("web");
        pc.setService("service");
        pc.setServiceImpl("service.impl");
        pc.setMapper("dao");
        pc.setEntity("entity");
        pc.setXml("xml");
        mpg.setPackageInfo(pc);

        // 执行生成
        mpg.execute();

    }

}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/115708.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

ATJ2158界面绘制LVGL---定时器

LVGL定时器 在lv_timer.c中有相关的操作函数 Create a timer&#xff08;创建定时器&#xff09; LVGL 有一个内置的定时器系统。可以注册一个函数以定期调用它。定时器在lv_timer_handler()中被处理和调用&#xff0c;它需要每隔几毫秒调用一次 Ready and Reset&#xff0…

fio磁盘压测工具

文章目录背景安装测试如何模拟现实中的IOfio参数解释【1】随机读测试【2】随机写测试【3】 顺序读测试【4】 顺序写测试numjobs5 测试随机读随机写顺序读顺序写blktracefio 模拟真实IO场景查看 blktrace 记录的结果将结果转化为二进制文件使用 fio 重放日志结论背景 因为是虚拟…

Oracle 备份与恢复常见的七大问题

为了最大限度保障数据的安全性&#xff0c;同时能在不可预计灾难的情况下保证数据的快速恢复&#xff0c;需要根据数据的类型和重要程度制定相应的备份和恢复方案。在这个过程中&#xff0c;DBA的职责就是要保证数据库&#xff08;其它数据由其它岗位负责&#xff09;的高可用和…

Linux常用操作(下)

目录 文件传输 全局查找 管道符 统计数目 vim快捷键 软件安装 用户和组 文件权限 文件传输 yum install lrzsz -y rpm -qa |grep lrzsz 完成后直接将文件拖入xshell即可 全局查找 grep 字符串 文件名 grep colea * grep -r colea *//递归全局查找 管道符 ps -ef…

边缘AI概述

随着移动计算和物联网&#xff08;IoT&#xff09;应用程序的爆炸性增长&#xff0c;数十亿移动和物联网设备正在连接到互联网&#xff0c;在网络边缘生成大量数据。因此&#xff0c;在云数据中心收集大量数据会产生极高的延迟和网络带宽使用。 因此&#xff0c;迫切需要将人工…

K8S——调用亲和性

k8s-调度亲和性 简介 Scheduler 是 kubernetes 的调度器&#xff0c;主要的任务是把定义的 pod 分配到集群的节点上。听起来非常简单&#xff0c;但有 很多要考虑的问题&#xff1a; 公平&#xff1a;如何保证每个节点都能被分配资源资源高效利用&#xff1a;集群所有资源最…

为什么NoSQL数据库这么受欢迎?

大数据时代&#xff0c;NoSQL数据库是企业构建数据能力的核心工具之一。近期&#xff0c;在2022腾讯全球数字生态大会NoSQL数据库专场上&#xff0c;腾讯云发布了多项NoSQL产品能力升级&#xff0c;并重点讲解了其背后的自研技术要点及实现细节&#xff0c;分享了腾讯云NoSQL为…

利用Python自动生成请假条,实现高效摸鱼

哈喽兄弟们&#xff0c;今天咱们来实现用Python来批量生成请假条&#xff0c;这回既学了东西又做了事情&#xff0c;两不误~ 本文就将基于一个真实的办公案例进行讲解如何提取Excel内容并创建Word 主要将涉及以下三个知识点 openpyxl 读取 Excel 文件python-docx 写入 Word …

org.springframework.jdbc.BadSqlGrammarException: Error updating database

&#x1f497;wei_shuo的个人主页 &#x1f4ab;wei_shuo的学习社区 &#x1f310;Hello World &#xff01; org.springframework.jdbc.BadSqlGrammarException: Error updating database 报错信息&#xff1a; org.springframework.jdbc.BadSqlGrammarException: Error updat…

Python基础入门(一)

文章目录前言Python起源简介常量和表达式什么是变量变量的语法变量的定义变量的命名规则使用变量变量的类型动态类型的变量注释注释是什么注释的基本语法注释的书写规范输入输出通过控制台输出格式化输出输入转义字符运算符算数运算符关系运算符逻辑运算符赋值运算符复合赋值运…

Python高频面试题——迭代器和可迭代对象

无论是面试测试还是运维涉及到python编码岗位时&#xff0c;迭代器和可迭代对象都是绕不开的一个问题&#xff0c;本文对这两个概念进行重点讲解&#xff0c;本文从什么是迭代讲起&#xff0c;然后介绍迭代器和可迭代对象二者的区别&#xff0c;最后通过for 循环和自定义迭代器…

150万奖金:首届6G智能无线通信系统大赛正式上线

通信与人工智能技术的深度融合已成为无线通信系统发展的最重要方向之一&#xff0c;面向6G&#xff0c;通信与AI融合的角度和深度将进一步扩展&#xff0c;迎接“无限”可能。在6G研究的关键发展阶段&#xff0c;由IMT-2030(6G)推进组主办&#xff0c;中国信息通信研究院、华为…

【折腾服务器 3】群晖学习版中安装 Active Backup for Business 及相关配置 =)

Catch UP 书接上回&#xff0c;在 ESXi 中安装了群晖系统&#xff0c;这个系统主要是用来给 Windows 物理机做备份的&#xff0c;因此在本片主要讲解如何配置 Active Backup for Business 软件。 Chapter 1 设置存储空间 上一篇博客中&#xff0c;安装群晖时分配了一个 32GB…

rancher2.6.2 单机及高可用部署

rancher2.6.2 单机及高可用部署 文章目录rancher2.6.2 单机及高可用部署前言单机部署高可用部署k8s集成前言 1、服务器准备 单机部署&#xff1a; 机器名IP地址部署内容cpu核心数内存(G)硬盘(G)rancher-master192.168.0.18rancher2450 高可用部署&#xff1a; 机器名IP地址…

Linux环境下通过命令行连接WIFI

一. 前言 在调试ARTIK时由于Ubuntu系统不是图形化界面&#xff0c;需要下载相关安装包时发现未联网&#xff0c;因此对Linux下采用命令行连接wifi的具体操作步骤进行总结&#xff0c;对自己在操作过程中遇到的相关问题解决方法进行介绍&#xff0c;同时对于LINUX下无线网络调试…

JUC(一):线程池

个人博客地址&#xff1a; http://xiaohe-blog.top/index.php/archives/14/ 文章目录1. 为什么要使用线程池2. Executor3. ThreadPoolExecutor3.1 七个参数3.2 任务队列3.3 拒绝策略4. 创建线程池5. Executors5.1 CachedThreadPool5.2 FixedThreadPool5.3 SingleThreadExecutor…

Vue3 异步组件 suspense

vue在解析我们的组件时&#xff0c; 是通过打包成一个 js 文件&#xff0c;当我们的一个组件 引入过多子组件是&#xff0c;页面的首屏加载时间 由最后一个组件决定 优化的一种方式就是采用异步组件 &#xff0c;先给慢的组件一个提示语或者 骨架屏 &#xff0c;内容回来在显示…

大话测试数据(一)

导读&#xff1a;测试数据的准备至关重要&#xff0c;无论是手工测试还是自动化测试都要以良好的测试数据准备为基础。本文为霍格沃兹测试学院特邀嘉宾&#xff0c;某互联网巨头企业资深测试技术专家刘晓光&#xff08;skytraveler&#xff09;老师对测试数据管理实践的思考总结…

【K3s】第3篇 解决K3s状态一直是ContainerCreating

目录 1、遇到问题 2、问题解决 2.1 查看docker服务 2.2 增加docker中国镜像源 必看项 2.3 解决docker pull失败 3、结果展示 1、遇到问题 安装部署完k3s时遇到如下问题&#xff1a; sudo kubectl get pods -A pod 容器状态一直为&#xff1a;ContainerCreating 查看容…

现有项目集成seata的记录

背景&#xff1a;现有项目为springcloudnacos 的。但是没有分布式事务处理机制&#xff0c;偶发数据问题&#xff0c;现需要引入seata进行全局事务管理。简单记录一下改造和学习过程&#xff0c;过一段时间自己100%会忘的一干二净&#xff0c;并没有对其进行很深的研究。 前期…