Mybatis-Plus 代码生成器模板(粗略解析)

使用mybatis-plus代码生成器可以减少手动编写一些类的时间,更高效的进行开发。

导入maven依赖

<!--MybatisPlus-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.3.2</version>
        </dependency>
        <!--代码生成器-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.3.2</version>
        </dependency>
        <!--性能分析器-->
        <dependency>
            <groupId>p6spy</groupId>
            <artifactId>p6spy</artifactId>
            <version>3.9.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity-engine-core</artifactId>
            <version>2.2</version>
        </dependency>

如果使用了swagger需要导入响应的依赖

        <!--swagger-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.10.5</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-spring-webmvc</artifactId>
            <version>2.10.5</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.10.5</version>
        </dependency>

生成器模板

package com.x.x;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.FieldFill;
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.po.TableFill;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;

import java.util.ArrayList;

public class GeneratorCode {

    public static void main(String[] args) {
        AutoGenerator generator = new AutoGenerator();
        //全局配置
        GlobalConfig globalConfig = new GlobalConfig();
        //项目路径
        String projectPath = System.getProperty("user.dir");
        globalConfig.setOutputDir(projectPath+"/src/main/java");

        //作者名
        globalConfig.setAuthor("D");
        //是否打开输出目录 是否直接打开目录
        globalConfig.setOpen(false);
        //是否覆盖
        globalConfig.setFileOverride(false);
        //去掉Service的I前缀
        globalConfig.setServiceName("%sService");
        //ID策略 IdType.AUTO自增
        globalConfig.setIdType(IdType.AUTO);
        //日期类型 DateType.ONLY_DATE 使用 java.util.date 的Date
        //DateType.SQL_PACK java.sql 包下的Date
        //推荐使用 DateType.TIME_PACK 会使用 java.time.LocalDateTime jdk1.8以上才支持
        globalConfig.setDateType(DateType.TIME_PACK);
        //开启 swagger2 模式
        globalConfig.setSwagger2(true);

        generator.setGlobalConfig(globalConfig);

        //设置数据源
        DataSourceConfig dataSourceConfig = new DataSourceConfig();
        dataSourceConfig.setUrl("jdbc:p6spy:mysql://localhost:6379/salary?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC&useSSL=false");
        dataSourceConfig.setDriverName("com.p6spy.engine.spy.P6SpyDriver");
        dataSourceConfig.setUsername("root");
        dataSourceConfig.setPassword("123456");
        //MySql数据库
        dataSourceConfig.setDbType(DbType.MYSQL);

        generator.setDataSource(dataSourceConfig);

        // 包的配置
        PackageConfig packageConfig = new PackageConfig();
        //父包模块名
        packageConfig.setModuleName("");
        //包名 根据自己的包进行编写
        packageConfig.setParent("com.x.x");
        packageConfig.setEntity("model.pojo");
        packageConfig.setMapper("mapper");
        packageConfig.setService("service");
        packageConfig.setController("controller");

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        //映射的表名
        //可以直接使用 strategy.setInclude("admin","user"); 多个表一起生成
        strategy.setInclude("admin");
        //映射规则 NamingStrategy.no_change 则以表的字段直接输出不转换
        //NamingStrategy.underline_to_camel下划线转驼峰命名  user_id -> userId
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        //设置Lombok需要导入依赖
        strategy.setEntityLombokModel(true);
        //控制器是否为RestController
        strategy.setRestControllerStyle(true);
        //逻辑删除的名字
        strategy.setLogicDeleteFieldName("deleted");
        //乐观锁
        strategy.setVersionFieldName("version");
        //自动填充配置
        //这里注意填写数据库中的字段名
        TableFill create_time = new TableFill("gmt_create", FieldFill.INSERT);
        TableFill update_time = new TableFill("gmt_modified", FieldFill.INSERT_UPDATE);
        TableFill deleted = new TableFill("deleted", FieldFill.INSERT);
        ArrayList<TableFill> tableFills = new ArrayList<>();
        tableFills.add(create_time);
        tableFills.add(update_time);
        tableFills.add(deleted);
        strategy.setTableFillList(tableFills);

        //驼峰转连字符
        //@RequestMapping("/managerUserActionHistory") -> @RequestMapping("/manager-user-action-history")
        strategy.setControllerMappingHyphenStyle(true);

        //数据库表配置
        generator.setStrategy(strategy);

        //包相关配置
        generator.setPackageInfo(packageConfig);

        //执行
        generator.execute();
    }
}

粗解

//作者名
globalConfig.setAuthor("D");

设置作者名建议使用IDEA进行统一配置。
在这里插入图片描述

//设置时间类型
globalConfig.setDateType(DateType.TIME_PACK);

设置时间类型建议使用jdk1.8的LocalDateTime

  1. LocalDateTime比Date在多线程的时候更加的安全(date需要使用SimpleDateFormat对时间进行格式化,而SimpleDateFormat是不安全的。)
  2. LocalDateTime直接输出是一个可读的

包名

//包名
packageConfig.setParent("com.zsc.salary");

在新建项目的时候设置包名建议使用自己的域名(倒序)进行命名,这样不会出现重复的包名。
例如:x.com —> com.x.项目

映射的表名

//映射的表名
strategy.setInclude("admin");

映射的表名可以多个表一起生成

strategy.setInclude("admin","user");

自动填充配置

//
TableFill create_time = new TableFill("gmt_create", FieldFill.INSERT);
TableFill update_time = new TableFill("gmt_modified", FieldFill.INSERT_UPDATE);
TableFill deleted = new TableFill("deleted", FieldFill.INSERT);
ArrayList<TableFill> tableFills = new ArrayList<>();
tableFills.add(create_time);
tableFills.add(update_time);
tableFills.add(deleted);
strategy.setTableFillList(tableFills);

这里可以根据自己的数据库设计进行增加。需要与mybatis-plus自动填充功能一起使用。(当然也可以之类在数据库中设置默认值)

mybatis-plus自动填充功能

package com.zsc.salary.bean;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * <p>
 * 配置Mybatis-plus 自动填充
 * </p>
 *
 * @author D
 * @version 1.0
 * @date 2020/6/26 14:10
 */
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

	//insertFill在插入的时候会自动调用
    @Override
    public void insertFill(MetaObject metaObject) {

        log.info("start insert fill ....");
        this.strictInsertFill(metaObject, "gmt_create", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "gmt_modified", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "deleted", Boolean.class, false);
    }

	//updateFill在更新的时候会自动调用
    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("start update fill ....");
        this.strictInsertFill(metaObject, "gmt_modified", LocalDateTime.class, LocalDateTime.now());

    }
}

映射规则

//映射规则 NamingStrategy.no_change 则以表的字段直接输出不转换
//NamingStrategy.underline_to_camel下划线转驼峰命名  user_id -> userId
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);

在java中字段的命名一般遵守驼峰命名(阿里规范),所有在这里使用下划线转驼峰命名。

开启 swagger2 模式

globalConfig.setSwagger2(true);

在springboot中建议使用swagger或者其他相应的,可以直接对接口进行测试或者生成接口文档。

猜你喜欢

转载自blog.csdn.net/d875708765/article/details/107792277