Use mybatis_plus to automatically generate entity classes, controller layer, service layer, and mapper layer based on data tables, greatly improving development efficiency.

Code generator Mybatis_Plus greatly improves development efficiency

Today I have summarized another major function of mybatis_plus here, which can greatly improve our development efficiency!

We all know that the most boring and essential process in the development process is to create the corresponding entity class based on the data table, as well as the control layer and business that interact with the front end to implement the service layer interface and its implementation class impl, and The mapper layer interface that interfaces with the persistence layer (database)

If the above process can be automatically generated, it will greatly reduce the developer's workload and improve development efficiency!

So the automatic code generation function of mybatis_plus came into being!

The following is the implementation process

Prepare data:

建表语句 表一:
DROP TABLE IF EXISTS `borrow_info`;
CREATE TABLE `borrow_info`  (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '编号',
  `user_id` bigint(20) NOT NULL DEFAULT 0 COMMENT '借款用户id',
  `amount` decimal(10, 2) NULL DEFAULT NULL COMMENT '借款金额',
  `period` int(11) NULL DEFAULT NULL COMMENT '借款期限',
  `borrow_year_rate` decimal(10, 2) NULL DEFAULT NULL COMMENT '年化利率',
  `return_method` tinyint(3) NULL DEFAULT NULL COMMENT '还款方式 1-等额本息 2-等额本金 3-每月还息一次还本 4-一次还本',
  `money_use` tinyint(3) NULL DEFAULT NULL COMMENT '资金用途',
  `status` tinyint(3) NOT NULL DEFAULT 0 COMMENT '状态(0:未提交,1:审核中, 2:审核通过, -1:审核不通过)',
  `create_time` timestamp(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间',
  `update_time` timestamp(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) ON UPDATE CURRENT_TIMESTAMP(0) COMMENT '更新时间',
  `is_deleted` tinyint(1) NOT NULL DEFAULT 0 COMMENT '逻辑删除(1:已删除,0:未删除)',
  PRIMARY KEY (`id`) USING BTREE,
  INDEX `idx_user_id`(`user_id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 6 CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '借款信息表' ROW_FORMAT = DYNAMIC;
建表语句 表二:
DROP TABLE IF EXISTS `borrower`;
CREATE TABLE `borrower`  (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '编号',
  `user_id` bigint(20) NOT NULL DEFAULT 0 COMMENT '用户id',
  `name` varchar(30) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '姓名',
  `id_card` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '0' COMMENT '身份证号',
  `mobile` varchar(11) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '手机',
  `sex` tinyint(3) NULL DEFAULT NULL COMMENT '性别(1:男 0:女)',
  `age` tinyint(3) NULL DEFAULT NULL COMMENT '年龄',
  `education` tinyint(3) NULL DEFAULT NULL COMMENT '学历',
  `is_marry` tinyint(1) NULL DEFAULT NULL COMMENT '是否结婚(1:是 0:否)',
  `industry` tinyint(3) NULL DEFAULT NULL COMMENT '行业',
  `income` tinyint(3) NULL DEFAULT NULL COMMENT '月收入',
  `return_source` tinyint(3) NULL DEFAULT NULL COMMENT '还款来源',
  `contacts_name` varchar(30) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '联系人名称',
  `contacts_mobile` varchar(11) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '联系人手机',
  `contacts_relation` tinyint(3) NULL DEFAULT NULL COMMENT '联系人关系',
  `status` tinyint(3) NOT NULL DEFAULT 0 COMMENT '状态(0:未认证,1:认证中, 2:认证通过, -1:认证失败)',
  `create_time` timestamp(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间',
  `update_time` timestamp(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) ON UPDATE CURRENT_TIMESTAMP(0) COMMENT '更新时间',
  `is_deleted` tinyint(1) NOT NULL DEFAULT 0 COMMENT '逻辑删除(1:已删除,0:未删除)',
  PRIMARY KEY (`id`) USING BTREE,
  UNIQUE INDEX `uk_user_id`(`user_id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '借款人' ROW_FORMAT = DYNAMIC;

First introduce the required dependencies in the pom.xml file of the project module:

            <!--mybatis-plus-->
            <dependency>
                <groupId>com.baomidou</groupId>
                <artifactId>mybatis-plus-boot-starter</artifactId>
                <version>最新版本号</version>
            </dependency>
            <!--mybatis-plus 代码生成器-->
            <dependency>
                <groupId>com.baomidou</groupId>
                <artifactId>mybatis-plus-generator</artifactId>
                <version>最新版本号</version>
            </dependency>
            <!-- Mybatis Plus 代码生成器模板引擎,  -->
            <dependency>
                <groupId>org.apache.velocity</groupId>
                <artifactId>velocity-engine-core</artifactId>
                <version>最新版本号</version>
            </dependency>

Then create a test class in the test test package for automatically generating code implementation:

package com.atguigu.srb.core;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

public class CodeGenerator {
    
    
    @Test
    public void genCode() {
    
    

        // 1、创建代码生成器对象mpg
        AutoGenerator mpg = new AutoGenerator();

        // 2、创建全局配置对象 根据需要设置全局配置的参数
        GlobalConfig gc = new GlobalConfig();
        //获取当前系统用户所创建的当前项目的路径
        String projectPath = System.getProperty("user.dir");
        //设置代码自动生成的文件所存储的路径地址
        gc.setOutputDir(projectPath + "/src/main/java");
        //设置项目作者的名字
        gc.setAuthor("baomidou");
        //如果为true 就会在代码生成后以资源管理器的形式自动打开所生成文件
        gc.setOpen(false); //生成后是否打开资源管理器
        //根据要求选择service包下的类名是否以I开头
        gc.setServiceName("%sService");	//去掉Service接口的首字母I
        //数据表的主键生成策略
        gc.setIdType(IdType.AUTO); //主键策略
        gc.setSwagger2(true);//开启Swagger2模式
        //将全局配置对象设置到代码生成器的对象中
        mpg.setGlobalConfig(gc);

        // 3、创建数据源配置对象
        DataSourceConfig dsc = new DataSourceConfig();
        //设置数据库的访问地址
        dsc.setUrl("jdbc:mysql://localhost:3306/db_baomidou?serverTimezone=GMT%2B8&characterEncoding=utf-8");
        //设置数据库驱动配置
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        //数据库的用户名
        dsc.setUsername("root");
        //数据库密码
        dsc.setPassword("1234");
        //设置数据库的种类
        dsc.setDbType(DbType.MYSQL);
        // 将数据源的配置对象也加入到代码生成器对象中
        mpg.setDataSource(dsc);

        // 4、创建包配置对象
        PackageConfig pc = new PackageConfig();
        //文件的包存储路径
        pc.setParent("com.baomidou.mybatis.plus");
        //设置实体类的包名结构 一般情况下可以直接将实体类放在pojo包下
        //pc.setEntity("pojo");
        //当然也可以放在pojo下的entity包下
        pc.setEntity("pojo.entity"); //此对象与数据库表结构一一对应,通过 DAO 层向上传输数据源对象。
        mpg.setPackageInfo(pc);

        // 5、创建策略配置对象
        StrategyConfig strategy = new StrategyConfig();
        //开启类以及接口名的驼峰命名规则
        strategy.setNaming(NamingStrategy.underline_to_camel);//数据库表映射到实体的命名策略
        //开启实体类属性名的驼峰命名规则
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);//数据库表字段映射到实体的命名策略
        //是否在数据表所对应的实体类上开启lombok (也就是加上@Data注解)
        strategy.setEntityLombokModel(true); // lombok
        //给逻辑删除字段加上逻辑删除注解@TableLogic    (1:表示已经逻辑删除 0:表示并未逻辑删除)
        //所谓的逻辑删除就是在统计表中数据的条数时 不将已经逻辑删除的数据(is_deleted字段为0的数据)计算在内
        strategy.setLogicDeleteFieldName("is_deleted");//逻辑删除字段名
        //根据阿里巴巴开发规范 对实体类的某些属性名字做了规范
        //对于数据表中的is_xxx的字段名 在转换为实体属性名的时候去掉is
        strategy.setEntityBooleanColumnRemoveIsPrefix(true);//去掉布尔值的is_前缀(确保tinyint(1))
        //启用restful api风格  在对应的controller类上加上@RestController注解
        //如果为false 则加上的是@Controller注解
        //而@RestController=@Controller+@ResponseBody
        //会使得后端返回的数据的格式是json格式
        strategy.setRestControllerStyle(true); //restful api风格控制器  返回json
        mpg.setStrategy(strategy);

        // 6、执行
        mpg.execute();
    }
}

That’s it! ! ! !

Guess you like

Origin blog.csdn.net/Coastlise/article/details/132372365