• 信步漫谈之MyBatisPlus——自动生成代码



    1 目的

    使用MybatisPlus的自动生成工具,进行自动生成代码,留存操作方式,可使用伪代码实现。

    2 程序结构

    com.alfred.mybatisplus.autogenerator
        ∟ pom.xml
        ∟ src
            ∟ main
                ∟ java
                    ∟ com
                        ∟ alfred
                            ∟ mybatisplus
                                ∟ autogenerator
                                    ∟ CodeGenerator.java
                ∟ resources
                    ∟ templates
                        ∟ mapper.xml.ftl
            ∟ test
                ∟ java
    

    3 程序代码

    • CodeGenerator.java
    package com.alfred.mybatisplus.autogenerator;
    
    import com.baomidou.mybatisplus.annotation.IdType;
    import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
    import com.baomidou.mybatisplus.core.toolkit.StringPool;
    import com.baomidou.mybatisplus.core.toolkit.StringUtils;
    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.NamingStrategy;
    import com.baomidou.mybatisplus.generator.engine.AbstractTemplateEngine;
    import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
    
    import java.util.*;
    
    
    /**
     * @Author: alfred
     * @Date: 2021/1/21
     * @description:
     */
    public class CodeGenerator {
    
        private static String PROJECT_PATH = "com.alfred.mybatisplus.autogenerator";
        private static String TABLE_NAME = "";
        private static String ENTITY_NAME = "";
    
        /**
         * 全局配置
         */
        private static final String AUTHOR = "alfred";
    
        /**
         * 数据源配置
         */
        private static final String DB_URL = "jdbc:mysql://127.0.0.1:3306/mybatisplus";
        private static final String DB_DRIVER = "com.mysql.jdbc.Driver";
        private static final String DB_USERNAME = "root";
        private static final String DB_PASS = "123456";
    
        /**
         * <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.isNotBlank(ipt)) {
                    return ipt;
                }
            }
            throw new MybatisPlusException("请输入正确的" + tip + "!");
        }
    
        public static void main(String[] args) {
            //输入参数
            TABLE_NAME = scanner("表名");
            ENTITY_NAME = scanner("实体名");
            //代码生成器
            AutoGenerator mpg = new AutoGenerator();
            //全局配置
            mpg.setGlobalConfig(getGlobalConfig());
            //数据源配置
            mpg.setDataSource(getDataSourceConfig());
            //包配置
            mpg.setPackageInfo(getPackageInfoConfig());
            //模板配置
            mpg.setTemplate(getTemplateConfig());
            //模板引擎配置
            mpg.setTemplateEngine(getTemplateEngineConfig());
            //策略配置
            mpg.setStrategy(getStrategyConfig());
            //自定义配置
            mpg.setCfg(getInjectionConfig());
            //生成
            mpg.execute();
        }
    
        private static GlobalConfig getGlobalConfig() {
            GlobalConfig gc = new GlobalConfig();
    //        String projectPath = System.getProperty("user.dir");
            //作者
            gc.setAuthor(AUTHOR);
            //是否打开输出目录
            gc.setOpen(false);
            // 是否覆盖目录
            gc.setFileOverride(true);
            // 是否Swagger2注解
            gc.setSwagger2(true);
            // 是否开启二级缓存
            gc.setEnableCache(false);
            gc.setBaseResultMap(true);
            gc.setBaseColumnList(true);
            //主键策略
            gc.setIdType(IdType.INPUT);
            //设置命名格式
            gc.setEntityName("%s");
            gc.setControllerName("%sController");
            gc.setMapperName("%sMapper");
            gc.setXmlName("%sMapper");
            gc.setServiceName("I%sService");
            gc.setServiceImplName("%sServiceImpl");
            return gc;
        }
    
        private static DataSourceConfig getDataSourceConfig() {
            DataSourceConfig dsc = new DataSourceConfig();
            dsc.setUrl(DB_URL);
            dsc.setDriverName(DB_DRIVER);
            dsc.setUsername(DB_USERNAME);
            dsc.setPassword(DB_PASS);
            return dsc;
        }
    
        private static PackageConfig getPackageInfoConfig() {
            PackageConfig pc = new PackageConfig();
            //设置主包名
            pc.setParent(PROJECT_PATH);
            return pc;
        }
    
        private static TemplateConfig getTemplateConfig() {
            TemplateConfig tc = new TemplateConfig();
            return tc;
        }
    
        private static AbstractTemplateEngine getTemplateEngineConfig() {
            // 使用 freemarker 模板引擎
            return new FreemarkerTemplateEngine();
        }
    
        private static StrategyConfig getStrategyConfig() {
            StrategyConfig strategy = new StrategyConfig();
            strategy.setNaming(NamingStrategy.underline_to_camel);
            strategy.setColumnNaming(NamingStrategy.underline_to_camel);
            strategy.setEntityLombokModel(true);
            strategy.setRestControllerStyle(true);
            strategy.setInclude(TABLE_NAME);
            strategy.setControllerMappingHyphenStyle(true);
            strategy.setEntityTableFieldAnnotationEnable(true);
            return strategy;
        }
    
        private static InjectionConfig getInjectionConfig() {
            //自定义注入信息配置
            Map<String, Object> map = new HashMap<>();
            //此处传递自定义参数后,可在模板ftl文件中使用${cfg.my_define}引用该参数
            map.put("my_define", "my_define");
            InjectionConfig cfg = new InjectionConfig() {
                @Override
                public void initMap() {
                    this.setMap(map);
                }
            };
            cfg.setFileOutConfigList(getFileOutConfig());
            return cfg;
        }
    
        private static List<FileOutConfig> getFileOutConfig() {
            List<FileOutConfig> focList = new ArrayList<>();
            String mapperTemplatePath = "/templates/mapper.xml.ftl";
            // 自定义配置会被优先输出
            focList.add(new FileOutConfig(mapperTemplatePath) {
                @Override
                public String outputFile(TableInfo tableInfo) {
                    return PROJECT_PATH + "/src/main/resources/mapper/" + ENTITY_NAME + "Mapper" + StringPool.DOT_XML;
                }
            });
    
            String controllerTemplatePath = "/templates/controller.java.ftl";
            // 自定义配置会被优先输出
            focList.add(new FileOutConfig(controllerTemplatePath) {
                @Override
                public String outputFile(TableInfo tableInfo) {
                    return PROJECT_PATH + "/src/main/java/com/alfred/mybatisplus/autogenerator/controller/" + ENTITY_NAME + "Controller" + StringPool.DOT_JAVA;
                }
            });
    
            String entityTemplatePath = "/templates/entity.java.ftl";
            // 自定义配置会被优先输出
            focList.add(new FileOutConfig(entityTemplatePath) {
                @Override
                public String outputFile(TableInfo tableInfo) {
                    return PROJECT_PATH + "/src/main/java/com/alfred/mybatisplus/autogenerator/entity/" + ENTITY_NAME + StringPool.DOT_JAVA;
                }
            });
    
            String serviceTemplatePath = "/templates/service.java.ftl";
            // 自定义配置会被优先输出
            focList.add(new FileOutConfig(serviceTemplatePath) {
                @Override
                public String outputFile(TableInfo tableInfo) {
                    return PROJECT_PATH + "/src/main/java/com/alfred/mybatisplus/autogenerator/service/I" + ENTITY_NAME + "Service" + StringPool.DOT_JAVA;
                }
            });
    
            String serviceImplTemplatePath = "/templates/serviceImpl.java.ftl";
            // 自定义配置会被优先输出
            focList.add(new FileOutConfig(serviceImplTemplatePath) {
                @Override
                public String outputFile(TableInfo tableInfo) {
                    return PROJECT_PATH + "/src/main/java/com/alfred/mybatisplus/autogenerator/service/impl/" + ENTITY_NAME + "ServiceImpl" + StringPool.DOT_JAVA;
                }
            });
            return focList;
        }
    
    }
    
    • mapper.xml.ftl
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="${package.Mapper}.${table.mapperName}">
            <!-- ${cfg.my_define} -->
        <#if enableCache>
            <!-- 开启二级缓存 -->
            <cache type="org.mybatis.caches.ehcache.LoggingEhcache"/>
        </#if>
    </mapper>
    
    • pom.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <parent>
            <groupId>com.alfred.version</groupId>
            <artifactId>version-mybatisplus-general</artifactId>
            <version>1.0.0-SNAPSHOT</version>
        </parent>
        <modelVersion>4.0.0</modelVersion>
        <groupId>com.alfred.mybatisplus</groupId>
        <artifactId>mybatisplus-autogenerator</artifactId>
        <version>1.0.0-SNAPSHOT</version>
        <description>
            功能:使用MybatisPlus的自动生成工具,进行自动生成代码,留存操作方式,可使用伪代码实现。
        </description>
    
        <dependencies>
            <dependency>
                <groupId>com.baomidou</groupId>
                <artifactId>mybatis-plus-boot-starter</artifactId>
            </dependency>
            <dependency>
                <groupId>com.baomidou</groupId>
                <artifactId>mybatis-plus</artifactId>
            </dependency>
            <dependency>
                <groupId>com.baomidou</groupId>
                <artifactId>mybatis-plus-generator</artifactId>
            </dependency>
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <type>jar</type>
                <scope>compile</scope>
            </dependency>
            <dependency>
                <groupId>org.freemarker</groupId>
                <artifactId>freemarker</artifactId>
                <scope>compile</scope>
            </dependency>
        </dependencies>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.1</version>
                    <configuration>
                        <source>${java.version}</source>
                        <target>${java.version}</target>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <configuration>
                        <excludes>
                            <exclude>com.baomidou.mybatisplus.samples.generator.MpGeneratorTest</exclude>
                        </excludes>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>org.codehaus.mojo</groupId>
                    <artifactId>cobertura-maven-plugin</artifactId>
                    <version>2.7</version>
                    <configuration>
                        <formats>
                            <format>html</format>
                            <format>xml</format>
                        </formats>
                        <instrumentation>
                            <ignoreMethodAnnotations>
                                <ignoreMethodAnnotation>lombok.Generated</ignoreMethodAnnotation>
                            </ignoreMethodAnnotations>
                        </instrumentation>
                        <check/>
                    </configuration>
                    <executions>
                        <execution>
                            <goals>
                                <goal>clean</goal>
                            </goals>
                        </execution>
                    </executions>
                </plugin>
            </plugins>
        </build>
    
    </project>
    
    • 数据库sql
    SET FOREIGN_KEY_CHECKS=0;
    
    -- ----------------------------
    -- Table structure for user
    -- ----------------------------
    DROP TABLE IF EXISTS `user`;
    CREATE TABLE `user` (
      `id` bigint(20) NOT NULL COMMENT '主键ID',
      `name` varchar(30) COLLATE utf8_bin DEFAULT NULL COMMENT '姓名',
      `age` int(11) DEFAULT NULL COMMENT '年龄',
      `email` varchar(50) COLLATE utf8_bin DEFAULT NULL COMMENT '邮箱',
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
    

    4 生成效果

    • 输入生成条件
    请输入表名:
    user
    请输入实体名:
    User
    
    • 生成目录结构
    com.alfred.mybatisplus.autogenerator
        ∟ pom.xml
        ∟ src
            ∟ main
                ∟ java
                    ∟ com
                        ∟ alfred
                            ∟ mybatisplus
                                ∟ autogenerator
                                    ∟ CodeGenerator.java
                                    ∟ controller
                                        ∟ UserController.java
                                    ∟ entity
                                        ∟ User.java
                                    ∟ service
                                        ∟ impl
                                            ∟ UserServiceImpl.java
                                        ∟ IUserService.java
                ∟ resources
                    ∟ mapper
                        ∟ UserMapper.xml
                    ∟ templates
                        ∟ mapper.xml.ftl
            ∟ test
                ∟ java
    

    5 其他

    • 模板文件可参考mybatis-plus-generator-3.4.1.jar包内的templates目录下,官方提供的默认模板
      各类模板引擎官方都提供有模板参考,未指定则使用默认模板,可自定义

    6 参考资料(感谢)

    mybatis-plus官网指南
    官网示例项目集合

  • 相关阅读:
    ubuntu 14.04搭建PHP项目基本流程
    linux下 lvm 磁盘扩容
    LVM基本介绍与常用命令
    Linux LVM逻辑卷配置过程详解
    mysql 5.7中的用户权限分配相关解读!
    linux系统维护时的一些小技巧,包括系统挂载新磁盘的方法!可收藏!
    linux系统内存爆满的解决办法!~
    源、更新源时容易出现的问题解决方法
    NV显卡Ubuntu14.04更新软件导致登录死循环,不过可以进入tty模式
    一些要注意的地方
  • 原文地址:https://www.cnblogs.com/alfredinchange/p/14314089.html
Copyright © 2020-2023  润新知