mybatis-plus代码生成使用

导读:本篇文章讲解 mybatis-plus代码生成使用,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

前言

最近搞得一个项目持久层用的就是mp,这是一个基于mybatis的一个增强版持久层框架,强大性不言而喻。并且自带一个代码生成器,所以今天我们就来折腾一下这个代码生成器!

配置

根据官网的配置,我们创建一个Maven工程,添加依赖

<!--lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <!--读取yml文件-->
        <dependency>
            <groupId>org.yaml</groupId>
            <artifactId>snakeyaml</artifactId>
            <version>1.23</version>
        </dependency>
        <!-- mybatis-plus依赖 -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
        </dependency>
        <!--MySQL-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

然后根据官网文档将示例代码拷下来:

// 演示例子,执行 main 方法控制台输入模块表名回车自动生成对应项目目录中
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.isNotBlank(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("请输入正确的" + tip + "!");
    }

    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("jobob");
        gc.setOpen(false);
        // gc.setSwagger2(true); 实体属性 Swagger2 注解
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://localhost:3306/ant?useUnicode=true&useSSL=false&characterEncoding=utf8");
        // dsc.setSchemaName("public");
        dsc.setDriverName("com.mysql.jdbc.Driver");//驱动
        dsc.setUsername("root");
        dsc.setPassword("密码");
        mpg.setDataSource(dsc);

        // 包配置
        PackageConfig pc = new PackageConfig();
        //pc.setModuleName(scanner("模块名"));//如果你需要这个,那么他就会在你的包下生成一个同名包
        pc.setParent("com.baomidou.ant");//包名
        mpg.setPackageInfo(pc);

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

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

        // 自定义输出配置
        List<FileOutConfig> focList = new ArrayList<>();
        // 自定义配置会被优先输出
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
                return projectPath + "/src/main/resources/mapper/" + pc.getModuleName()
                        + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;//不变,会自动在resources目录下生成mapper文件夹
            }
        });
        /*
        cfg.setFileCreate(new IFileCreate() {
            @Override
            public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
                // 判断自定义文件夹是否需要创建
                checkDir("调用默认方法创建的目录,自定义目录用");
                if (fileType == FileType.MAPPER) {
                    // 已经生成 mapper 文件判断存在,不想重新生成返回 false
                    return !new File(filePath).exists();
                }
                // 允许生成模板文件
                return true;
            }
        });
        */
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();

        // 配置自定义输出模板
        //指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
        // templateConfig.setEntity("templates/entity2.java");
        // templateConfig.setService();
        // templateConfig.setController();

        templateConfig.setXml(null);
        mpg.setTemplate(templateConfig);

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        //strategy.setSuperEntityClass("你自己的父类实体,没有就不用设置!");
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        // 公共父类
        //strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!");
        // 写于父类中的公共字段
        strategy.setSuperEntityColumns("id");
        strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
        strategy.setControllerMappingHyphenStyle(true);
        strategy.setTablePrefix(pc.getModuleName() + "_");
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }
}

加强配置

上面那样已经OK,但是我还想把里面的有些配置灵活设置,所以增加了一个yml配置文件

# mybatis-plus代码生成器配置
gen:
  author: 朝花不迟暮
  projectPath: /squad_generator/src/main/java
  swagger2: true
  dscUrl: jdbc:mysql://localhost:3306/squad?useUnicode=true&useSSL=false&characterEncoding=utf8
  driveName: com.mysql.jdbc.Driver
  username: root
  password: 123456
  basePackage: com.zhbcm.squad
  outPutDir: /src/main/java
  resourceDir: /src/main/resources
  resourceDirName: /mapper
  moduleName: squad_generator

我又在网上找了一个工具类,专门解读配置文件的。或许你会想到比如用@value或者用@ConfigurationProperties注解来读取,但是这是要托管到spring容器里面的,我的代码生成类并不在spring里,所以只能用读流形式进行读取

package com.zhbcm.squad.common.utils;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ResourceUtils;
import org.yaml.snakeyaml.Yaml;

import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * yml读取工具类
 *
 * @author 朝花不迟暮
 * @version 1.0
 * @date 2021/2/8 13:56
 */
public class YmlUtil
{
    private static final Logger LOGGER = LoggerFactory.getLogger(YmlUtil.class);

    private static String bootstrap_file = "classpath:conf/generator.yml";

    private static Map<String, String> result = new HashMap<>();

    /**
     * 根据文件名获取yml的文件内容
     *
     * @param filePath
     * @param keys     第一个参数对应第一个key,第二个参数对应第二个key 比如spring.name下的所有 就是两个参数、
     *                 getYmlByFileName(bootstrap_file,"spring", "name");
     * @return
     */
    public static Map<String, String> getYmlByFileName(String filePath, String... keys)
    {
        result = new HashMap<>();
        if (filePath == null) filePath = bootstrap_file;
        InputStream in = null;
        try
        {
            File file = ResourceUtils.getFile(filePath);
            in = new BufferedInputStream(new FileInputStream(file));
            Yaml props = new Yaml();
            Object obj = props.loadAs(in, Map.class);
            Map<String, Object> param = (Map<String, Object>) obj;

            for (Map.Entry<String, Object> entry : param.entrySet())
            {
                String key = entry.getKey();
                Object val = entry.getValue();
                if (keys.length != 0 && !keys[0].equals(key))
                {
                    continue;
                }
                if (val instanceof Map)
                {
                    forEachYaml(key, (Map<String, Object>) val, 1, keys);
                } else
                {
                    result.put(key, val.toString());
                }
            }
            return result;
        } catch (FileNotFoundException e)
        {
            LOGGER.error(e.getMessage(), e);
        } finally
        {
            if (in != null)
            {
                try
                {
                    in.close();
                } catch (IOException e)
                {
                    LOGGER.error(e.getMessage(), e);
                }
            }
        }
        return null;
    }

    /**
     * 根据key获取值
     *
     * @param key
     * @return
     */
    public static String getValue(String key) throws FileNotFoundException
    {
        Map<String, String> map = getYmlByFileName(null);
        if (map == null) return null;
        return map.get(key);
    }


    /**
     * 遍历yml文件,获取map集合
     *
     * @param key_str
     * @param obj
     * @param i
     * @param keys
     */
    public static void forEachYaml(String key_str, Map<String, Object> obj, int i, String... keys)
    {
        for (Map.Entry<String, Object> entry : obj.entrySet())
        {
            String key = entry.getKey();
            Object val = entry.getValue();
            if (keys.length > i && !keys[i].equals(key))
            {
                continue;
            }
            String str_new = "";
            if (StringUtils.isNotEmpty(key_str))
            {
                str_new = key_str + "." + key;
            } else
            {
                str_new = key;
            }
            if (val instanceof Map)
            {
                forEachYaml(str_new, (Map<String, Object>) val, ++i, keys);
                i--;
            } else
            {
                result.put(str_new, val.toString());
            }
        }
    }

    public static void main(String[] args) throws FileNotFoundException
    {
        Map<String, String> ymlByFileName = getYmlByFileName(bootstrap_file, "gen");
        Set<Map.Entry<String, String>> entries = ymlByFileName.entrySet();
        for (Map.Entry<String, String> entry : entries)
        {
            System.out.println(entry.getKey() + "===" + entry.getValue());
        }
    }
}

我又写了个配置属性类

package com.zhbcm.squad.common.properties;

import com.zhbcm.squad.common.utils.YmlUtil;
import lombok.Data;

import java.util.Map;

/**
 * @author 朝花不迟暮
 * @version 1.0
 * @date 2021/2/8 14:16
 */
@Data
public class GeneratorProperties
{
    private String author;
    private String projectPath;
    private Boolean swagger2;
    private String dscUrl;
    private String driveName;
    private String userName;
    private String password;
    private String basePackage;
    private String outPutDir;
    private String resourceDir;
    private String resourceDirName;
    private String moduleName;

    public static GeneratorProperties build()
    {
        Map<String, String> map = YmlUtil.getYmlByFileName("classpath:conf/generator.yml", "gen");
        GeneratorProperties properties = new GeneratorProperties();
        properties.setAuthor(map.get("gen.author"));
        properties.setProjectPath(map.get("gen.projectPath"));
        properties.setSwagger2(Boolean.valueOf(map.get("gen.swagger2")));
        properties.setDscUrl(map.get("gen.dscUrl"));
        properties.setDriveName(map.get("gen.driveName"));
        properties.setUserName(map.get("gen.username"));
        properties.setPassword(map.get("gen.password"));
        properties.setBasePackage(map.get("gen.basePackage"));
        properties.setOutPutDir(map.get("gen.outPutDir"));
        properties.setResourceDir(map.get("gen.resourceDir"));
        properties.setResourceDirName(map.get("gen.resourceDirName"));
        properties.setModuleName(map.get("gen.moduleName"));
        return properties;
    }
}

配置结束,将原来需要动态的地方动态化,就结束了!

package com.zhbcm.squad;

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.FreemarkerTemplateEngine;
import com.zhbcm.squad.common.properties.GeneratorProperties;

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

/**
 * @author 朝花不迟暮
 * @version 1.0
 * @date 2021/2/8 13:08
 */
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.isNotBlank(ipt))
            {
                return ipt;
            }
        }
        throw new MybatisPlusException("请输入正确的" + tip + "!");
    }

    public static void main(String[] args)
    {
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();
        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");
        gc.setOutputDir(projectPath + "/" + GeneratorProperties.build().getModuleName() +
                GeneratorProperties.build().getOutPutDir());
        gc.setAuthor(GeneratorProperties.build().getAuthor());
        gc.setOpen(false);
        gc.setSwagger2(GeneratorProperties.build().getSwagger2()); //实体属性 Swagger2 注解
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl(GeneratorProperties.build().getDscUrl());
        // dsc.setSchemaName("public");
        dsc.setDriverName(GeneratorProperties.build().getDriveName());
        dsc.setUsername(GeneratorProperties.build().getUserName());
        dsc.setPassword(GeneratorProperties.build().getPassword());
        mpg.setDataSource(dsc);

        // 包配置
        PackageConfig pc = new PackageConfig();
        //pc.setModuleName(scanner("模块名"));
        pc.setParent(GeneratorProperties.build().getBasePackage());
        mpg.setPackageInfo(pc);

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

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

        // 自定义输出配置
        List<FileOutConfig> focList = new ArrayList<>();
        // 自定义配置会被优先输出
        focList.add(new FileOutConfig(templatePath)
        {
            @Override
            public String outputFile(TableInfo tableInfo)
            {
                // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
                return projectPath + "/" + GeneratorProperties.build().getModuleName() +
                        GeneratorProperties.build().getResourceDir() +
                        GeneratorProperties.build().getResourceDirName()
                        + pc.getModuleName()
                        + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });
        /*
        cfg.setFileCreate(new IFileCreate() {
            @Override
            public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
                // 判断自定义文件夹是否需要创建
                checkDir("调用默认方法创建的目录,自定义目录用");
                if (fileType == FileType.MAPPER) {
                    // 已经生成 mapper 文件判断存在,不想重新生成返回 false
                    return !new File(filePath).exists();
                }
                // 允许生成模板文件
                return true;
            }
        });
        */
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();

        // 配置自定义输出模板
        //指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
        // templateConfig.setEntity("templates/entity2.java");
        // templateConfig.setService();
        // templateConfig.setController();

        templateConfig.setXml(null);
        mpg.setTemplate(templateConfig);

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
//        strategy.setSuperEntityClass("你自己的父类实体,没有就不用设置!");
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        // 公共父类
        //strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!");
        // 写于父类中的公共字段
        strategy.setSuperEntityColumns("id");
        strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
        strategy.setControllerMappingHyphenStyle(true);
        strategy.setTablePrefix(pc.getModuleName() + "_");
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }
}

如有问题请联系QQ:707409741

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/16356.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!