当前位置: 首页 > news >正文

mybatis-plus 代码生成器使用

Mybatis-plus 代码生成器


Mybatis-plus 我就不过多的介绍了,有兴趣的可以看一下官网 官网链接

快速生成Controller、Entity、Mapper 、Service、Impl 以及Resource 下的 xml文件和目录

博主使用的SpringBoot 2.1.3 , mysql-connector-java 6中的 com.mysql.cj.jdbc.Driver
生成结构图:

生成结构图

POM依赖:

<!-- mp -->
		<dependency>
			<groupId>com.baomidou</groupId>
			<artifactId>mybatis-plus-boot-starter</artifactId>
			<version>3.0.3</version>
		</dependency>


		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>

		<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-freemarker -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-freemarker</artifactId>
			<version>2.1.3.RELEASE</version>
		</dependency>

		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>

OK ,直接开始,打开 官网 找到代码生成器 ,配置数据库驱动,用户名和密码就可以直接执行了,博主用的是 mysql

package com.mp.test.service.impl;

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 java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

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.isNotEmpty(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);
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://192.168.2.11:3306/hx_testm?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8");
        // dsc.setSchemaName("public");
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("123456");
        mpg.setDataSource(dsc);

        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setModuleName(scanner("模块名"));
        pc.setParent("com.mp.test");
        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;
            }
        });

        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("com.baomidou.ant.common.BaseEntity");
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        strategy.setSuperControllerClass("com.baomidou.ant.common.BaseController");
        strategy.setInclude(scanner("表名"));
        strategy.setSuperEntityColumns("id");
        strategy.setControllerMappingHyphenStyle(true);
        strategy.setTablePrefix(pc.getModuleName() + "_");
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }

}

相关文章:

  • java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to ***
  • you *might* want to use the less safe log_bin_trust_function_creators variable
  • node.js websocket.io 搭建 websocket 通信服务
  • Mysql 定时器
  • mysql 存储过程 遍历
  • mysql复制表结构的几种方式
  • TO_CHAR 和 TO_DATE的一些用法
  • Spark:学习笔记
  • linux:常用基本命令
  • Spark:数据倾斜处理一般从什么地方入手
  • MapReduce:中map和reduce的数量设置问题
  • MapReduce: 计数器(Counter)
  • Hive:HiveQL中如何排查数据倾斜问题
  • Java:字符序列:String,StringBuilder,StringBuffer三者的区别
  • Hive:分区和分桶
  • [ JavaScript ] 数据结构与算法 —— 链表
  • C语言笔记(第一章:C语言编程)
  • Eureka 2.0 开源流产,真的对你影响很大吗?
  • JS正则表达式精简教程(JavaScript RegExp 对象)
  • MySQL几个简单SQL的优化
  • npx命令介绍
  • python_bomb----数据类型总结
  • react 代码优化(一) ——事件处理
  • SQLServer插入数据
  • vue--为什么data属性必须是一个函数
  • webpack+react项目初体验——记录我的webpack环境配置
  • webpack项目中使用grunt监听文件变动自动打包编译
  • 互联网大裁员:Java程序员失工作,焉知不能进ali?
  • 欢迎参加第二届中国游戏开发者大会
  • 每天10道Java面试题,跟我走,offer有!
  • 爬虫模拟登陆 SegmentFault
  • 前端技术周刊 2019-01-14:客户端存储
  • 适配iPhoneX、iPhoneXs、iPhoneXs Max、iPhoneXr 屏幕尺寸及安全区域
  • 算法---两个栈实现一个队列
  • 微服务核心架构梳理
  • 小李飞刀:SQL题目刷起来!
  • 在Docker Swarm上部署Apache Storm:第1部分
  • 怎样选择前端框架
  • 自制字幕遮挡器
  • 移动端高清、多屏适配方案
  • ​油烟净化器电源安全,保障健康餐饮生活
  • "无招胜有招"nbsp;史上最全的互…
  • (3)llvm ir转换过程
  • (C语言)fread与fwrite详解
  • (紀錄)[ASP.NET MVC][jQuery]-2 純手工打造屬於自己的 jQuery GridView (含完整程式碼下載)...
  • (一)Linux+Windows下安装ffmpeg
  • (一)为什么要选择C++
  • (已解决)什么是vue导航守卫
  • (转)Oracle存储过程编写经验和优化措施
  • (转载)虚幻引擎3--【UnrealScript教程】章节一:20.location和rotation
  • . ./ bash dash source 这五种执行shell脚本方式 区别
  • .NET DevOps 接入指南 | 1. GitLab 安装
  • .Net MVC4 上传大文件,并保存表单
  • .net 逐行读取大文本文件_如何使用 Java 灵活读取 Excel 内容 ?
  • .NET/C# 编译期能确定的字符串会在字符串暂存池中不会被 GC 垃圾回收掉