mybatis-plus代码生成,实体类不生成父类属性

本文详细介绍了如何使用MyBatis Plus和Beetl模版引擎进行代码生成,包括配置依赖、自定义模版及排除父类属性等高级技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、参考文档:

官方文档其实说的很清楚了,可能有个别地方有点不太清楚。

  mybatis-plus官方: https://mp.baomidou.com/guide/generator.html  

模版引擎用的beetl,之前没怎么接触过这块,不过感觉beetl有点像是写jsp一样,上手快。

  beetl官方: http://ibeetl.com/guide/#/beetl/

二、具体实现,说明可以看注释,更详细的配置可以看官方文档。

依赖:

       <!--代码生成-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.2.0</version>
        </dependency>
        <!--代码生成使用的模版引擎-->
        <dependency>
            <groupId>com.ibeetl</groupId>
            <artifactId>beetl</artifactId>
            <version>2.9.3</version>
        </dependency>

 

 

import cn.hutool.core.collection.CollectionUtil;
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.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.BeetlTemplateEngine;

import java.util.HashMap;
import java.util.Map;

public class Main {
    //核心类,所有操作配置都围绕该类展开。
    private static final AutoGenerator mpg = new AutoGenerator();
    //获取项目目录
    private static final String projectPath = System.getProperty("user.dir");
    //项目基础包
    private static final String Package = "com.mz.mzservice";
    //子模块包名,最终生成的是类似  com.mz.mzservice.dev 这样的
    private static final String ModuleName = "dev";

    public static void main(String[] args) {
        //数据库连接配置
        DataSourceConfig dataSourceConfig = new DataSourceConfig();
        dataSourceConfig.setUrl("jdbc:mysql://localhost:3306/test?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=GMT%2B8");
        dataSourceConfig.setDriverName("com.mysql.cj.jdbc.Driver");
        dataSourceConfig.setUsername("root");
        dataSourceConfig.setPassword("root");
        mpg.setDataSource(dataSourceConfig);
        //公用的一些配置,一看就懂的就不加注释了。
        GlobalConfig globalConfig = new GlobalConfig();
        globalConfig.setOutputDir(projectPath + "/src/main/java");
        globalConfig.setAuthor("sun");
        //日期类型的字段使用哪个类型,默认是 java8的 日期类型,此处改为 java.util.date
        globalConfig.setDateType(DateType.ONLY_DATE);
        //是否覆盖 已存在文件,默认 false 不覆盖
        globalConfig.setFileOverride(false);
        //mapper.xml 是否生成 ResultMap,默认 false 不生成
        globalConfig.setBaseResultMap(true);
        //mapper.xml 是否生成 ColumnList,默认 false 不生成
        globalConfig.setBaseColumnList(true);
        //生成的实体类名字,增加前后缀的 ,下面的mapper xml 同理,另外还有controller和service的名称配置
//        globalConfig.setEntityName("%sEntity");
        globalConfig.setMapperName("%sMapper");
        globalConfig.setXmlName("%sMapper");
        //是否生成完成后打开资源管理器
        globalConfig.setOpen(false);
        mpg.setGlobalConfig(globalConfig);

        PackageConfig pc = new PackageConfig();
        pc.setParent(Package);
        pc.setModuleName(ModuleName);
        mpg.setPackageInfo(pc);

        StrategyConfig strategy = new StrategyConfig();
        //支持正则表达式,字符串数组。 和 Exclude 二选一
        // TODO 此处使用正则生成时,提示有些bug。
        //  被正则过滤的表会提示 “^dev_.*$” 表不存在,其实需要生成代码的表已经正常生成完毕了。
        strategy.setInclude("^dev_.*$");
        //  不需要生成的表
        //  strategy.setExclude("sequence");
        //此处配置为 下划线转驼峰命名
        strategy.setNaming(NamingStrategy.underline_to_camel);
        //生成的字段 是否添加注解,默认false
        strategy.setEntityTableFieldAnnotationEnable(true);
        //表前缀,配置后 生成的的代码都会把前缀去掉
//        strategy.setTablePrefix("dev_");
        //实体类的基础父类。没有可以不配置。
        strategy.setSuperEntityClass("com.mz.mzservice.entity.BaseEntity");
        //这里本来以为配置上 生成的实体类就没有父类的属性了,但其实不是。
        //如何去掉父类属性,下面有说明。
        strategy.setSuperEntityColumns("creater","createTime","editor","editTime","remark");
        //controller,基础父类
        strategy.setSuperControllerClass("com.mz.mzservice.controller.BaseController");
        //是否启用 Lombok
        strategy.setEntityLombokModel(true);
        //是否启用 builder 模式 例:new DevDevice().setDealerId("").setDeviceCode("");
        strategy.setEntityBuilderModel(true);
        mpg.setStrategy(strategy);

        InjectionConfig in = new InjectionConfig() {
            @Override
            public void initMap() {
                Map<String, Object> map = new HashMap<String, Object>();
                //自定义配置,在模版中cfg.superColums 获取
                // TODO 这里解决子类会生成父类属性的问题,在模版里会用到该配置
                map.put("superColums", this.getConfig().getStrategyConfig().getSuperEntityColumns());
                this.setMap(map);
            }
        };
        in.setFileOutConfigList(CollectionUtil.newArrayList(new FileOutConfig("/templates/mapper.xml.btl") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义mapper xml输出目录
                return projectPath + "/src/main/resources/mapper/" + ModuleName
                        + "/" + tableInfo.getMapperName()  + StringPool.DOT_XML;
            }
        }));
        mpg.setCfg(in);
        TemplateConfig templateConfig = new TemplateConfig();
        //自定义模版
        templateConfig.setController("/templates/btl/controller.java");
        templateConfig.setEntity("/templates/btl/entity.java");
        //关闭默认的mapper xml生成
        templateConfig.setXml(null);
        mpg.setTemplate(templateConfig);
        //使用beetl模版引擎
        mpg.setTemplateEngine(new BeetlTemplateEngine());
        mpg.execute();
    }

}

三、自定义模版,这里我只粘贴出来,子类不生成父类属性的地方。修改是基于官方模版的。

说明:大概逻辑是判断字段名是否包含在之前在代码里配置的父类字段。如果包含则直接continue。

entity.java.btl

 

 

 

 

四、官方的默认模版位置

 

### MyBatis-Plus 3 自动生成功能及用法 MyBatis-Plus 是一款增强型的 MyBatis 框架,提供了许多便捷的功能,其中包括代码自动生成工具。通过该功能,开发者能够快速生成实体类、Mapper 接口、Service 层及其实现类以及其他相关组件,从而显著提升开发效率。 #### 添加依赖 为了使用 MyBatis-Plus代码生成器,首先需要在项目的 `pom.xml` 文件中引入必要的依赖项: ```xml <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-generator</artifactId> <version>3.x.x</version> <!-- 替换为最新版本 --> </dependency> <dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.31</version> <!-- 或其他兼容版本 --> </dependency> ``` 上述配置中的 `mybatis-plus-generator` 是用于代码生成的核心模块,而 `freemarker` 则作为模板引擎支持生成代码文件[^1]。 #### 配置代码生成器 以下是基于 MyBatis-Plus 3 的代码生成器的一个典型配置示例: ```java import com.baomidou.mybatisplus.generator.AutoGenerator; import com.baomidou.mybatisplus.generator.config.DataSourceConfig; import com.baomidou.mybatisplus.generator.config.GlobalConfig; import com.baomidou.mybatisplus.generator.config.PackageConfig; import com.baomidou.mybatisplus.generator.config.StrategyConfig; public class CodeGenerator { public static void main(String[] args) { AutoGenerator mpg = new AutoGenerator(); // 全局配置 GlobalConfig gc = new GlobalConfig(); String projectPath = System.getProperty("user.dir"); gc.setOutputDir(projectPath + "/src/main/java"); // 输出目录 gc.setAuthor("Your Name"); // 设置作者名 gc.setOpen(false); // 是否打开输出目录 mpg.setGlobalConfig(gc); // 数据源配置 DataSourceConfig dsc = new DataSourceConfig(); dsc.setUrl("jdbc:mysql://localhost:3306/your_database?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC"); dsc.setDriverName("com.mysql.cj.jdbc.Driver"); dsc.setUsername("root"); dsc.setPassword("password"); mpg.setDataSource(dsc); // 包配置 PackageConfig pc = new PackageConfig(); pc.setParent("com.example.demo"); // 父包名 pc.setModuleName(null); // 模块名 mpg.setPackageInfo(pc); // 策略配置 StrategyConfig strategy = new StrategyConfig(); strategy.setInclude("table_name"); // 表名集合 strategy.setNaming(com.baomidou.mybatisplus.generator.config.rules.NamingStrategy.underline_to_camel); strategy.setColumnNaming(com.baomidou.mybatisplus.generator.config.rules.NamingStrategy.underline_to_camel); strategy.setEntityLombokModel(true); // 开启 Lombok 注解 mpg.setStrategy(strategy); // 执行生成 mpg.execute(); } } ``` 此代码片段展示了如何设置全局参数、数据源连接信息、包路径以及表策略等内容。其中,`setInclude()` 方法指定了要生成代码的目标数据库表名称;`setNaming()` 和 `setColumnNaming()` 定义了字段命名规则,通常采用下划线转驼峰的方式[^2]。 #### 功能扩展 除了基本的 CRUD 生成功能外,MyBatis-Plus 还允许用户定义额外的方法或属性。例如,在生成模型时可自动添加 Getter/Setters、toString() 方法等辅助逻辑: ```java strategy.setSuperEntityColumns("id", "create_time", "update_time"); // 继承父类通用字段 strategy.setControllerMappingHyphenStyle(true); // URL 中驼峰转连字符风格 ``` 这些选项进一步增强了框架灵活性并满足同场景需求[^3]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值