栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

使用mybatis-plus自动生成代码

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用mybatis-plus自动生成代码

一、介绍

本教程将使用mybatis-plus工具来自动生成Controll,Service,Entity,Mapper,Mapper.xml层代码。需要有两个基类。

  1. baseEntity:用来写一些公共字段。例如:创建时间,创建人等
  2. baseController:用来写基础公共的控制
二、实现步骤
  1.  首先在数据库中创建好 数据库和要生成代码对应的表。我这里已创建了account,customer,resource,role,role_resource这五个表。
  2. 
    
    ;
    
    ;
    
    ;
    ;
    ;
    ;
    CREATE DATABASE `project` ;
    
    USE `project`;
    
    
    
    DROp TABLE IF EXISTS `account`;
    
    CREATE TABLE `account` (
      `account_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键',
      `role_id` bigint(20) unsigned DEFAULT NULL COMMENT '角色id',
      `username` varchar(20) DEFAULT NULL COMMENT '用户名',
      `password` varchar(32) DEFAULT NULL COMMENT '密码',
      `salt` varchar(32) DEFAULT NULL COMMENT '加密盐',
      `real_name` varchar(50) DEFAULT NULL COMMENT '真实姓名',
      `sex` char(1) DEFAULT NULL COMMENT '性别',
      `email` varchar(100) DEFAULT NULL COMMENT '邮箱',
      `create_time` datetime DEFAULT NULL COMMENT '创建时间',
      `modified_time` datetime DEFAULT NULL COMMENT '修改时间',
      `create_account_id` bigint(20) unsigned DEFAULT NULL COMMENT '创建人',
      `modified_account_id` bigint(20) unsigned DEFAULT NULL COMMENT '修改人',
      `deleted` tinyint(3) unsigned DEFAULT 0 COMMENT '逻辑删除标识(0、否 1、是)',
      PRIMARY KEY (`account_id`) USING BTREE,
      KEY `FK_account_role_id` (`role_id`),
      CONSTRAINT `FK_account_role_id` FOREIGN KEY (`role_id`) REFERENCES `role` (`role_id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COMMENT='账号表';
    
    
    
    insert  into `account`(`account_id`,`role_id`,`username`,`password`,`salt`,`real_name`,`sex`,`email`,`create_time`,`modified_time`,`create_account_id`,`modified_account_id`,`deleted`) values (1,1,'mp','17a1640916cfa8356adc4336a72ac75d','ecbe5fac60d1499595fbb98dfa854501','程序牛人','男','mp@126.com','2020-11-10 13:46:32','2020-11-15 17:09:28',NULL,1,0);
    
    
    
    DROP TABLE IF EXISTS `customer`;
    
    CREATE TABLE `customer` (
      `customer_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键',
      `real_name` varchar(50) DEFAULT NULL COMMENT '真实姓名',
      `sex` char(1) DEFAULT NULL COMMENT '性别',
      `age` tinyint(3) unsigned DEFAULT NULL COMMENT '年龄',
      `email` varchar(100) DEFAULT NULL COMMENT '邮箱',
      `phone` varchar(11) DEFAULT NULL COMMENT '手机号码',
      `address` varchar(200) DEFAULT NULL COMMENT '地址',
      `create_time` datetime DEFAULT NULL COMMENT '创建时间',
      `modified_time` datetime DEFAULT NULL COMMENT '修改时间',
      `create_account_id` bigint(20) unsigned DEFAULT NULL COMMENT '创建人',
      `modified_account_id` bigint(20) unsigned DEFAULT NULL COMMENT '修改人',
      `deleted` tinyint(3) unsigned DEFAULT 0 COMMENT '逻辑删除标识(0、否 1、是)',
      PRIMARY KEY (`customer_id`) USING BTREE
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='客户表';
    
    
    
    
    
    DROP TABLE IF EXISTS `resource`;
    
    CREATE TABLE `resource` (
      `resource_id` bigint(20) unsigned NOT NULL COMMENT '主键',
      `parent_id` bigint(20) unsigned DEFAULT NULL COMMENT '父id',
      `resource_name` varchar(50) DEFAULT NULL COMMENT '资源名称',
      `resource_type` tinyint(4) DEFAULT NULL COMMENT '资源类型(0、目录 1、菜单 2、按钮)',
      `url` varchar(200) DEFAULT NULL COMMENT '请求地址',
      `code` varchar(100) DEFAULT NULL COMMENT '权限标识码',
      `sort` int(10) unsigned DEFAULT NULL COMMENT '排序',
      PRIMARY KEY (`resource_id`) USING BTREE
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='资源表';
    
    
    
    insert  into `resource`(`resource_id`,`parent_id`,`resource_name`,`resource_type`,`url`,`code`,`sort`) values (1,NULL,'系统管理',0,NULL,NULL,1),(2,NULL,'客户管理',0,NULL,NULL,2),(11,1,'角色管理',1,'role/toList',NULL,1),(12,1,'账号管理',1,'account/toList',NULL,2),(21,2,'客户管理',1,'customer/toList','customer',1);
    
    
    
    DROP TABLE IF EXISTS `role`;
    
    CREATE TABLE `role` (
      `role_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键',
      `role_name` varchar(50) DEFAULT NULL COMMENT '角色名称',
      `remark` varchar(200) DEFAULT NULL COMMENT '备注',
      `create_time` datetime DEFAULT NULL COMMENT '创建时间',
      `modified_time` datetime DEFAULT NULL COMMENT '修改时间',
      `create_account_id` bigint(20) unsigned DEFAULT NULL COMMENT '创建人',
      `modified_account_id` bigint(20) unsigned DEFAULT NULL COMMENT '修改人',
      `deleted` tinyint(3) unsigned DEFAULT 0 COMMENT '逻辑删除标识(0、否 1、是)',
      PRIMARY KEY (`role_id`) USING BTREE
    ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COMMENT='角色表';
    
    
    
    insert  into `role`(`role_id`,`role_name`,`remark`,`create_time`,`modified_time`,`create_account_id`,`modified_account_id`,`deleted`) values (1,'练习角色','练习角色',NULL,NULL,NULL,NULL,0);
    
    
    
    DROP TABLE IF EXISTS `role_resource`;
    
    CREATE TABLE `role_resource` (
      `role_resource_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键',
      `role_id` bigint(20) unsigned DEFAULT NULL COMMENT '角色id',
      `resource_id` bigint(20) unsigned DEFAULT NULL COMMENT '资源id',
      PRIMARY KEY (`role_resource_id`) USING BTREE,
      KEY `FK_role_resource_role_id` (`role_id`),
      KEY `FK_role_rerce_resourc_idD2D9` (`resource_id`),
      CONSTRAINT `FK_role_rerce_resourc_idD2D9` FOREIGN KEY (`resource_id`) REFERENCES `resource` (`resource_id`),
      CONSTRAINT `FK_role_resource_role_id` FOREIGN KEY (`role_id`) REFERENCES `role` (`role_id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8 COMMENT='角色资源表';
    
    
    
    insert  into `role_resource`(`role_resource_id`,`role_id`,`resource_id`) values (1,1,1),(2,1,2),(3,1,11),(4,1,12),(5,1,21);
    
    ;
    ;
    ;
    ;
    

 

 3.创建springboot项目,其中所用到的pom.xml文件内容如下图



    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.7.0
         
    
    cn.tedu
    project
    0.0.1-SNAPSHOT
    project
    Demo project for Spring Boot
    
        1.8
        3.4.1
        3.5.1
        2.5.6
        0.40
        5.4.7
        2.3.30
    
    
        
            org.springframework.boot
            spring-boot-starter-thymeleaf
        
        
            org.springframework.boot
            spring-boot-starter-web
        

        
            mysql
            mysql-connector-java
            runtime
        
        
            org.projectlombok
            lombok
            true
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
        
        
            com.baomidou
            mybatis-plus-boot-starter
            ${mybatis-plus.version}
        
        
        
            cn.hutool
            hutool-all
            ${hutool.version}
        
        
        
            org.webjars
            webjars-locator
            ${locator.version}
        
        
        
        
            org.webjars
            jquery
            ${jquery.version}
        
        
            org.webjars
            layui
            ${layui.version}
        
        
        
            com.baomidou
            mybatis-plus-generator
            ${mybatis-plus.version}
            test
        
        
            org.freemarker
            freemarker
            ${freemark.version}
            test
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
                
                    
                        
                            org.projectlombok
                            lombok
                        
                    
                
            
        
    


4.创建BaseController和BaseEntity类

package cn.tedu.controller;


public class BaseController {
}



package cn.tedu.entity;


public class BaseEntity {
}

5.创建代码生成类(将该类放到测试包里面)。该配置在mybatis-plus的官网MyBatis-Plus中已经有写。直接拿过来复制粘贴到自己的项目中,稍微修改一些配置即可。代码生成过程中需使用lombok插件,需提前在idea安装好。

package cn.tedu;

import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
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 org.apache.commons.lang3.StringUtils;

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

// 演示例子,执行 main 方法控制台输入模块表名回车自动生成对应项目目录中
public class CodeGenerator {

    
    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");
        projectPath = "D:\BackEnd\project\mpdemo";
        gc.setOutputDir(projectPath + "/src/main/java");  //生成路径,一般都是在/src/main/java下面
        gc.setAuthor("wen long");  //设置作者,设置为自己的
        gc.setOpen(false);
        gc.setServiceName("%sService"); //生成的service接口名字首字母是否为I,这样设置就没有了
        // gc.setSwagger2(true); 实体属性 Swagger2 注解
        gc.setFileOverride(true);   //第二次执行生成代码  会将第一次的覆盖掉,true即执行
        mpg.setGlobalConfig(gc);

        // 数据源配置   配置自己的数据库
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://localhost:3306/project?useUnicode=true&useSSL=false&characterEncoding=utf8");
        // 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("模块名")); //一般没有模块名,没有的话就可以注释掉
        pc.setParent("cn.tedu");   //配置为自己的包路径
        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 focList = new ArrayList<>();
        // 自定义配置会被优先输出
        String finalProjectPath = projectPath;
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
                return finalProjectPath + "/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("cn.tedu.entity.BaseEntity");  //自己的父类实体,没有就不需要设置
        strategy.setEntityLombokModel(true);    //使用lombok
        strategy.setRestControllerStyle(true);
        // 公共父类
        strategy.setSuperControllerClass("cn.tedu.controller.BaseController"); //自己的父类控制器,没有就不需要设置
        // 写于父类中的公共字段
        strategy.setSuperEntityColumns("id");
        strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
        strategy.setControllerMappingHyphenStyle(true);
//        strategy.setTablePrefix(pc.getModuleName() + "_");  //表名前缀
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }

}

 

4.执行结果:最后代码所生成的效果。 

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/988110.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号