zoukankan      html  css  js  c++  java
  • Mybatisplus<一> Springboot框架使用MybatisPlus代码自动生成器

    Mybatis-plus<一> Springboot框架使用MybatisPlus代码自动生成器

    Mybatis-plus官网: https://mp.baomidou.com/

    Demo GitHub下载地址(包含数据库建表sql,数据库数据与源代码):https://github.com/RJvon/Mybatis_plus_demo
    未经作者同意请勿转载

    Mybatis-plus简介

    MyBatis-Plus (简称 MP)是一个 MyBatis的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。

    AutoGenerator 是 MyBatis-Plus 的代码生成器,通过 AutoGenerator 可以快速生成 Entity、Mapper、Mapper XML、Service、Controller 等各个模块的代码,极大的提升了开发效率。

    1. MP 提供了大量的自定义设置,生成的代码完全能够满足各类型的需求

    2. MP 的代码生成器 和 Mybatis MBG 代码生成器: MP 的代码生成器都是基于 java 代码来生成。MBG 基于 xml 文件进行代码生成 MyBatis 的代码生成器可生成: 实体类、Mapper 接口、Mapper 映射文件 MP 的代码生成器可生成: 实体类(可以选择是否支持 AR)、Mapper 接口、Mapper 映射文件、 Service 层、Controller 层.

    3. 表及字段命名策略选择 在 MP 中,我们建议数据库表名 和 表字段名采用驼峰命名方式, 如果采用下划 线命名方式 请开启全局下划线开关,如果表名字段名命名方式不一致请注解指定,我们建议最好保持一致。

    这么做的原因是为了避免在对应实体类时产生的性能损耗,这样字段不用做映射就能直接和实体类对应。当然如果项目里不用考虑这点性能损耗,那么你采用下滑线也是没问题的,只需要在生成代码时配置 dbColumnUnderline 属性就可以 。

    新建Springboot项目,导入相关依赖

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.10</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.3.1.tmp</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.4.1</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.freemarker/freemarker -->
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.28</version>
        </dependency>
    
    </dependencies>
    

    在数据库中建一个表

    Demo GitHub下载地址:https://github.com/RJvon/Mybatis_plus_demo(数据库建表sql与源代码)
    数据库:New_employees
    新员工表:Employees
    create database New_employees default charset utf8;
    
    create table Employees
    (
    id integer not null,
    name varchar(20) not null,
    sex bit default 1,
    birth datetime not null,
    tel char(11),
    school varchar(255),
    primary key (id)
    );
    
    insert into Employees values 
    (101, '赵清华',1, '1996-5-5', '14894728324','清华大学'),
    (102, '钱北大',1, '1997-6-6','14894728321', '北京大学'),
    (103, '孙复旦',1, '1996-7-7', '14894728322','复旦大学'),
    (104, '李交通',0, '1999-8-8', '14894728323','上海交通大学'),
    (105, '周浙大',1, '1995-9-9', '14894728325','浙江大学'),
    (106, '吴中科',1, '1997-10-10','14894728326', '中国科学技术大学'),
    (107, '郑南京',0, '1983-11-11', '14894728327','南京大学'),
    (108, '王人民',1, '1999-12-12', '14894728328','中国人民大学'),
    (1001, '赵清',1, '1996-5-5', '14894728324','清华大学'),
    (1002, '钱北',1, '1997-6-6','14894728321', '北京大学'),
    (1003, '孙复',1, '1996-7-7', '14894728322','复旦大学'),
    (1004, '李交',0, '1999-8-8', null,'上海交通大学'),
    (1005, '周浙',1, '1995-9-9', '14894728325','浙江大学'),
    (1006, '吴中',1, '1997-10-10','14894728326', '中国科学技术大学'),
    (1007, '郑南',0, '1983-11-11', '14894728327','南京大学'),
    (1008, '王人',1, '1999-12-12', '14894728328','中国人民大学');
    

    代码自动生成器代码:

    package com.von.demo;
    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.*;
    import com.baomidou.mybatisplus.generator.config.*;
    import com.baomidou.mybatisplus.generator.config.builder.ConfigBuilder;
    import com.baomidou.mybatisplus.generator.config.po.TableInfo;
    import com.baomidou.mybatisplus.generator.config.rules.FileType;
    import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
    import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
    
    import java.io.File;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Scanner;
    
    /**
     * @author xueqing f
     * @version 1.0
     * @date 2021/7/31 16:33
     * Demo GitHub下载地址:https://github.com/RJvon/Mybatis_plus_demo(数据库建表sql与源代码)
     */
    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("xueqing");
            gc.setOpen(false);
            // gc.setSwagger2(true); 实体属性 Swagger2 注解
            mpg.setGlobalConfig(gc);
    
            // 数据源配置
            DataSourceConfig dsc = new DataSourceConfig();
            dsc.setUrl("jdbc:mysql://localhost:3306/New_employees?serverTimezone=GMT%2B8&useSSL=true");
            // dsc.setSchemaName("public");
            dsc.setDriverName("com.mysql.cj.jdbc.Driver");
            dsc.setUsername("root");
            dsc.setPassword("root");
            mpg.setDataSource(dsc);
    
            // 包配置
            PackageConfig pc = new PackageConfig();
            pc.setModuleName(scanner("module"));
            pc.setParent("com.von.demo");
            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/"
                            + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
                }
            });
            cfg.setFileOutConfigList(focList);
            mpg.setCfg(cfg);
    
            // 配置模板
            TemplateConfig templateConfig = new TemplateConfig();
    
            templateConfig.setXml(null);
            mpg.setTemplate(templateConfig);
    
            // 策略配置
            StrategyConfig strategy = new StrategyConfig();
            strategy.setNaming(NamingStrategy.underline_to_camel);
            strategy.setColumnNaming(NamingStrategy.underline_to_camel);
            strategy.setEntityLombokModel(true);
            strategy.setRestControllerStyle(true);
            // 写于父类中的公共字段
    //        strategy.setSuperEntityColumns("id");
            strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
            strategy.setControllerMappingHyphenStyle(true);
            strategy.setTablePrefix("_");
            mpg.setStrategy(strategy);
            mpg.setTemplateEngine(new FreemarkerTemplateEngine());
            mpg.execute();
        }
    
    }
    

    运行CodeGenerator:

    生成的代码结构:

  • 相关阅读:
    销售人员个人提升经典书籍推荐
    销售必看的书籍推荐
    我在公司敲代码,你却在家和老王………————程序员的那些梗
    某程序员动了公司的祖传代码"屎山",半年后怒交辞职报告!
    为什么说程序员的前三年不要太看重工资水平?
    好的员工关系应该是怎样的?
    粒子群优化算法(PSO)python 3实现
    Python基础篇-安装python
    Python设置matplotlib.plot的坐标轴刻度间隔以及刻度范围
    空TreeList添加节点不显示
  • 原文地址:https://www.cnblogs.com/aslanvon/p/15086187.html
Copyright © 2011-2022 走看看