MyBatisPlus3.x中使用代码生成器(全注释)

场景

MyBaitsPlus3.x与2.x是不一样的。这里使用3.0.1版本。

官方文档

https://mp.baomidou.com/guide/generator.html#%E4%BD%BF%E7%94%A8%E6%95%99%E7%A8%8B

这里在IDEA上的SpringBoot项目中进行代码生成测试。

实现

添加依赖

添加 代码生成器 依赖

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-generator</artifactId>
    <version>3.2.0</version>
</dependency>

注意:MyBatis-Plus 从 3.0.3 之后移除了代码生成器与模板引擎的默认依赖,需要手动添加相关依赖


            <!-- 模板引擎velocity start-->
            <dependency>
                <groupId>org.apache.velocity</groupId>
                <artifactId>velocity-engine-core</artifactId>
                <version>2.0</version>
            </dependency>
            <!-- 模板引擎velocity end-->
            <dependency>
                <groupId>com.baomidou</groupId>
                <artifactId>mybatis-plus-boot-starter</artifactId>
                <version>3.0.1</version>
            </dependency>

模板引擎

MyBatis-Plus 支持 Velocity(默认)、Freemarker、Beetl,用户可以选择自己熟悉的模板引擎。

注意!如果您选择了非默认引擎,需要在 AutoGenerator 中 设置模板引擎。

AutoGenerator generator = new AutoGenerator();

// set freemarker engine
generator.setTemplateEngine(new FreemarkerTemplateEngine());

// set beetl engine
generator.setTemplateEngine(new BeetlTemplateEngine());

// set custom engine (reference class is your custom engine class)
generator.setTemplateEngine(new CustomTemplateEngine());

编写代码

在test下新建单元测试类Generatortest.java

全局配置

 //全局配置
        GlobalConfig config = new GlobalConfig();
        //设置是否支持AR模式
        config.setActiveRecord(true)
                //设置生成代码的作者
                .setAuthor("badaoliumangqizhi")
                //设置输出代码的位置
                .setOutputDir("f:output")
                //.setEnableCache(false)// XML 二级缓存
                //.setBaseResultMap(true)// XML ResultMap
                //.setBaseColumnList(true)// XML columList
                //.setKotlin(true) 是否生成 kotlin 代码
                //设置是否覆盖原来的代码
                .setFileOverride(true);

数据源配置

//数据库连接url
        String dbUrl = "jdbc:sqlserver://;DatabaseName=";
        //数据源配置
        DataSourceConfig dataSourceConfig = new DataSourceConfig();
        //数据库类型 枚举
        dataSourceConfig.setDbType(DbType.SQL_SERVER)
                //设置url
                .setUrl(dbUrl)
                //设置用户名
                .setUsername("")
                //设置密码
                .setPassword("")
                //设置数据库驱动
                .setDriverName("com.microsoft.sqlserver.jdbc.SQLServerDriver")
                // 自定义数据库表字段类型转换【可选】
                .setTypeConvert(new MySqlTypeConvert() {
                    @Override
                    public DbColumnType processTypeConvert(GlobalConfig globalConfig, String fieldType) {
                        System.out.println("转换类型:" + fieldType);
                        //tinyint转换成Boolean
                         if ( fieldType.toLowerCase().contains( "tinyint" ) ) {
                            return DbColumnType.BOOLEAN;
                         }
                         //将数据库中datetime转换成date
                        if ( fieldType.toLowerCase().contains( "datetime" ) ) {
                            return DbColumnType.DATE;
                        }
                        return (DbColumnType) super.processTypeConvert(globalConfig, fieldType);
                    }
                });

策略配置

//策略配置
        StrategyConfig strategyConfig = new StrategyConfig();
        strategyConfig
                //全局大写命名是否开启
                .setCapitalMode(true)
                //【实体】是否为lombok模型
                .setEntityLombokModel(true)
                //表名生成策略  下划线转驼峰
                .setNaming(NamingStrategy.underline_to_camel)
                //自动填充设置
                //.setTableFillList(tableFillList)
                //修改替换成你需要的表名,多个表名传数组
                .setInclude("wms_receive_order");

集成注入配置

//注入全局设置
        new AutoGenerator().setGlobalConfig(config)
                //注入数据源配置
                .setDataSource(dataSourceConfig)
                //注入策略配置
                .setStrategy(strategyConfig)
                //设置包名信息
                .setPackageInfo(
                        new PackageConfig()
                                //提取公共父级包名
                                .setParent("com.badao.bus.sys")
                                //设置controller信息
                                .setController("controller")
                                //设置实体类信息
                                .setEntity("entity")
                )
                //设置自定义模板
                .setTemplate(
                        new TemplateConfig()
                                //.setXml(null)//指定自定义模板路径, 位置:/resources/templates/entity2.java.ftl(或者是.vm)
                                //注意不要带上.ftl(或者是.vm), 会根据使用的模板引擎自动识别
                                // 自定义模板配置,模板可以参考源码 /mybatis-plus/src/main/resources/template 使用 copy
                                // 至您项目 src/main/resources/template 目录下,模板名称也可自定义如下配置:
                                // .setController("...");
                                // .setEntity("...");
                                // .setMapper("...");
                                // .setXml("...");
                                // .setService("...");
                                 .setServiceImpl("templates/serviceImpl.java")
                )
                //开始执行代码生成
                .execute();
    }

完整生成器代码

package com.ws.test.generator;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.po.TableFill;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import org.junit.Test;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;

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

/**
 * Created by badado on 2019/4/25.
 */
public class Generatortest {
    @Test
    public void generateTest(){
        //全局配置
        GlobalConfig config = new GlobalConfig();
        //设置是否支持AR模式
        config.setActiveRecord(true)
                //设置生成代码的作者
                .setAuthor("badaoliumangqizhi")
                //设置输出代码的位置
                .setOutputDir("f:output")
                //.setEnableCache(false)// XML 二级缓存
                //.setBaseResultMap(true)// XML ResultMap
                //.setBaseColumnList(true)// XML columList
                //.setKotlin(true) 是否生成 kotlin 代码
                //设置是否覆盖原来的代码
                .setFileOverride(true);

       //******************************数据源配置***************************************
        //数据库连接url
        String dbUrl = "jdbc:sqlserver://;DatabaseName=";
        //数据源配置
        DataSourceConfig dataSourceConfig = new DataSourceConfig();
        //数据库类型 枚举
        dataSourceConfig.setDbType(DbType.SQL_SERVER)
                //设置url
                .setUrl(dbUrl)
                //设置用户名
                .setUsername("")
                //设置密码
                .setPassword("")
                //设置数据库驱动
                .setDriverName("com.microsoft.sqlserver.jdbc.SQLServerDriver")
                // 自定义数据库表字段类型转换【可选】
                .setTypeConvert(new MySqlTypeConvert() {
                    @Override
                    public DbColumnType processTypeConvert(GlobalConfig globalConfig, String fieldType) {
                        System.out.println("转换类型:" + fieldType);
                        //tinyint转换成Boolean
                         if ( fieldType.toLowerCase().contains( "tinyint" ) ) {
                            return DbColumnType.BOOLEAN;
                         }
                         //将数据库中datetime转换成date
                        if ( fieldType.toLowerCase().contains( "datetime" ) ) {
                            return DbColumnType.DATE;
                        }
                        return (DbColumnType) super.processTypeConvert(globalConfig, fieldType);
                    }
                });

        //******************************策略配置******************************************************
        // 自定义需要填充的字段 数据库中的字段
        List<TableFill> tableFillList = new ArrayList<>();
        tableFillList.add(new TableFill("gmt_modified", FieldFill.INSERT_UPDATE));
        tableFillList.add(new TableFill("modifier_id", FieldFill.INSERT_UPDATE));
        tableFillList.add(new TableFill("creator_id", FieldFill.INSERT));
        tableFillList.add(new TableFill("gmt_creat", FieldFill.INSERT));
        tableFillList.add(new TableFill("available_flag", FieldFill.INSERT));
        tableFillList.add(new TableFill("deleted_flag", FieldFill.INSERT));
        tableFillList.add(new TableFill("sync_flag", FieldFill.INSERT));
        //策略配置
        StrategyConfig strategyConfig = new StrategyConfig();
        strategyConfig
                //全局大写命名是否开启
                .setCapitalMode(true)
                //【实体】是否为lombok模型
                .setEntityLombokModel(true)
                //表名生成策略  下划线转驼峰
                .setNaming(NamingStrategy.underline_to_camel)
                //自动填充设置
                .setTableFillList(tableFillList)
                //修改替换成你需要的表名,多个表名传数组
                .setInclude("wms_receive_order");
        //集成注入设置
        //注入全局设置
        new AutoGenerator().setGlobalConfig(config)
                //注入数据源配置
                .setDataSource(dataSourceConfig)
                //注入策略配置
                .setStrategy(strategyConfig)
                //设置包名信息
                .setPackageInfo(
                        new PackageConfig()
                                //提取公共父级包名
                                .setParent("com.badao.bus.sys")
                                //设置controller信息
                                .setController("controller")
                                //设置实体类信息
                                .setEntity("entity")
                )
                //设置自定义模板
                .setTemplate(
                        new TemplateConfig()
                                //.setXml(null)//指定自定义模板路径, 位置:/resources/templates/entity2.java.ftl(或者是.vm)
                                //注意不要带上.ftl(或者是.vm), 会根据使用的模板引擎自动识别
                                // 自定义模板配置,模板可以参考源码 /mybatis-plus/src/main/resources/template 使用 copy
                                // 至您项目 src/main/resources/template 目录下,模板名称也可自定义如下配置:
                                // .setController("...");
                                // .setEntity("...");
                                // .setMapper("...");
                                // .setXml("...");
                                // .setService("...");
                                 .setServiceImpl("templates/serviceImpl.java")
                )
                //开始执行代码生成
                .execute();
    }
}

效果

运行测试

生成成功后会自动弹出生成代码的目录

 

  • 1
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论
可以在代码生成器的配置文件设置一个自定义的注释模板,在模板去除日期部分。具体操作如下: 1. 找到代码生成器的配置文件,一般为 `mybatis-plus-generator\src\main\resources\generator\generatorConfig.xml`。 2. 在配置文件找到 `commentGenerator` 配置项,修改为以下内容: ```xml <commentGenerator type="com.baomidou.mybatisplus.generator.config.CustomCommentGenerator"> <!-- 去除日期的注释模板 --> <property name="author" value="Your Name"/> <property name="dateFormat" value=""/> <property name="suppressDate" value="true"/> <property name="suppressAllComments" value="false"/> </commentGenerator> ``` 3. 新建一个 `CustomCommentGenerator` 类,继承 `DefaultCommentGenerator` 类,并重写 `addGeneralMethodComment()` 和 `addGeneralMethodAnnotation()` 方法。代码如下: ```java public class CustomCommentGenerator extends DefaultCommentGenerator { /** * 去除日期的方法注释模板 */ private static final String METHOD_COMMENT_TEMPLATE_WITHOUT_DATE = " * %s"; /** * 去除日期的方法注解模板 */ private static final String METHOD_ANNOTATION_TEMPLATE_WITHOUT_DATE = "@%s"; /** * 去除日期的方法注释 */ @Override public void addGeneralMethodComment(Method method, IntrospectedTable introspectedTable) { StringBuilder sb = new StringBuilder(); method.addJavaDocLine("/**"); sb.append(String.format(METHOD_COMMENT_TEMPLATE_WITHOUT_DATE, method.getName())); method.addJavaDocLine(sb.toString()); method.addJavaDocLine(" */"); } /** * 去除日期的方法注解 */ @Override public void addGeneralMethodAnnotation(Method method, IntrospectedTable introspectedTable, Set<FullyQualifiedJavaType> set) { String annotationName = null; for (FullyQualifiedJavaType type : set) { annotationName = type.getShortName(); break; } if (annotationName != null) { StringBuilder sb = new StringBuilder(); sb.append(String.format(METHOD_ANNOTATION_TEMPLATE_WITHOUT_DATE, annotationName)); method.addAnnotation(sb.toString()); } } } ``` 4. 在配置文件加入 `CustomCommentGenerator` 类的配置,修改 `commentGenerator` 为以下内容: ```xml <commentGenerator type="com.baomidou.mybatisplus.generator.config.CustomCommentGenerator"> <!-- 去除日期的注释模板 --> <property name="author" value="Your Name"/> <property name="suppressDate" value="true"/> <property name="suppressAllComments" value="false"/> </commentGenerator> ``` 5. 重新运行代码生成器,生成的代码注释的日期就被去除了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

霸道流氓气质

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值