[笔记]SpringBoot中使用MyBatis Plus Generator


Mybatis Plus是基于Mybatis进行改良的框架,提高了使用Mybatis框架进行数据库操作的效率,并能够使用生成器快速生成表对应的CURD Service类以及数据库实体类类,生成的实体类支持Lombok注解,非常简洁,且支持原生的Mybatis Mapper操作。

Mybatis框架虽然也有代码生成器,能够根据表生成对应的Example条件构造器从而进行数据库操作,但生成的实体类除了表字段外还充斥着其他代码,个人感觉不太喜欢,一个表实体类除了字段外,还充斥着其他大量代码,看起来太难受了(狗头

此文仅作为记录使用Mybatis Plus Generator生成代码的相关配置和操作

 

pom依赖:

        <!--MyBatis Plus-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.3.0</version>
        </dependency>
            <!--MyBatis Plus代码生成相关依赖-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.3.0</version>
        </dependency>
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.29</version>
        </dependency>
        <dependency>
            <groupId>com.ibeetl</groupId>
            <artifactId>beetl</artifactId>
            <version>3.0.15.RELEASE</version>
        </dependency>    

在SpringBoot项目的resouce目录添加MyBatisPlusGenerator.properties配置文件:

generator.jdbc.url=jdbc:mysql://127.0.0.1:3306/mydb?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai
generator.jdbc.driver=com.mysql.cj.jdbc.Driver
generator.jdbc.username=root
generator.jdbc.password=pwd

代码生成:

public class MyBatisPlusGenerator {

    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"); // 生成文件的输出目录,默认D根目录
        gc.setFileOverride(true); // 是否覆盖已有文件
        gc.setAuthor("ahrenJ");
        gc.setOpen(false); // 是否打开输出目录,默认true
        gc.setEnableCache(false); // 是否在xml中添加二级缓存配置,默认false
        gc.setSwagger2(false); // 开启 swagger2 模式,默认false

        gc.setEntityName("%sModel");
        gc.setMapperName("%sMapper");
        gc.setXmlName("%sMapper");
        gc.setServiceName("I%sService");
        gc.setServiceImplName("%sServiceImpl");
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        Properties properties = new Properties();
        try {
            File file = new ClassPathResource("/MyBatisPlusGenerator.properties").getFile();
            properties.load(new FileInputStream(file));
            dsc.setUrl(properties.getProperty("generator.jdbc.url"));
            dsc.setSchemaName("databaseName");
            dsc.setDriverName(properties.getProperty("generator.jdbc.driver"));
            dsc.setUsername(properties.getProperty("generator.jdbc.username"));
            dsc.setPassword(properties.getProperty("generator.jdbc.password"));
            mpg.setDataSource(dsc);
        } catch (IOException e) {
            throw new RuntimeException("数据源配置错误", e);
        }

        // 包名配置
        PackageConfig pc = new PackageConfig();
        pc.setModuleName("taoism");
        pc.setParent("com.music");
        pc.setEntity("model");
        mpg.setPackageInfo(pc);

        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
            }
        };

        // 如果模板引擎是 freemarker
        String templatePath = "/templates/mapper.xml.ftl";

        // 自定义输出配置
        List<FileOutConfig> focList = new ArrayList<>();
        // 自定义配置会被优先输出
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名
                return projectPath + "/taoism-db/src/main/resources/mapper/"
                        + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();
        // 配置自定义输出模板
        // templateConfig.setEntity();
        // templateConfig.setService();
        templateConfig.setController(null);
        templateConfig.setXml(null);
        mpg.setTemplate(templateConfig);

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel); // 数据库表映射到实体的命名策略
        strategy.setColumnNaming(NamingStrategy.underline_to_camel); // 数据库表字段映射到实体的命名策略, 未指定按照 naming 执行
        //strategy.setSuperEntityClass("com.shiyu.BaseEntity"); //自定义继承的Entity类全称,带包名
        //strategy.setSuperEntityColumns(new String[] {"id","gmtCreate","gmtModified"});// 自定义基础的Entity类,公共字段
        strategy.setEntityLombokModel(true); // 是否为lombok模型
        strategy.setEntityBooleanColumnRemoveIsPrefix(true); // Boolean类型字段是否移除is前缀
        strategy.setRestControllerStyle(false); // 生成 @RestController 控制器,个人觉得有点多余
        //strategy.setSuperControllerClass("com.music.taosim.ant.common.BaseController");
     //startegy.setInclude("tableName"); 当对某张表有所改动但只想重新生成这张表,可以这样设置
strategy.setControllerMappingHyphenStyle(true); // 驼峰转连字符 如 umps_user 变为 upms/user // strategy.setTablePrefix(pc.getModuleName() + "_"); // 表前缀 mpg.setStrategy(strategy); mpg.setTemplateEngine(new FreemarkerTemplateEngine()); //设置模板引擎类型,默认为 velocity mpg.execute(); } }

执行main方法,即可生成


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM