MyBatisPlus代码生成器


Springboot整合MybatisPlus

1.创建一个SpringBoot项目

2.导入相关依赖

<?xml version="1.0" encoding="UTF-8"?>

    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.2.2.RELEASE
         
    
    com.qbb
    simple-rights-management
    0.0.1-SNAPSHOT
    simple-rights-management
    simple-rights-management
    
        1.8
        3.4.1
        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
        
        
        
            com.baomidou
            mybatis-plus-boot-starter
            ${mybatis-plus.version}
        

        
        
            com.baomidou
            mybatis-plus-generator
            ${mybatis-plus.version}
            test
        
        
        
            org.freemarker
            freemarker
            ${freemark.version}
            test
        

    

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

3.编写代码生成器测试类(参考官方文档:MyBatisPlus)

package com.qbb.simplerightsmanagement;

import com.baomidou.mybatisplus.annotation.FieldFill;
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.builder.ConfigBuilder;
import com.baomidou.mybatisplus.generator.config.po.TableFill;
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.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * @author QiuQiu&LL (个人博客:https://www.cnblogs.com/qbbit)
 * @version 1.0
 * @date 2022-02-23  20:04
 * @Description:
 */
public class CodeGenerator {

    /**com/qbb/simplerightsmanagement
     * 

* 读取控制台内容 *

*/ 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("QIUQIU&LL"); // 代码生成完毕是否打开文件夹 gc.setOpen(false); // 设置不以I...Service开头 gc.setServiceName("%Service"); // gc.setDateType(DateType.TIME_PACK) 设置时间格式为Java8 // gc.setSwagger2(true); 实体属性 Swagger2 注解 mpg.setGlobalConfig(gc); // 数据源配置 DataSourceConfig dsc = new DataSourceConfig(); dsc.setUrl("jdbc:mysql://localhost:3306/mybatisplus?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=GMT%2B8"); // 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("com.qbb"); 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<>(); // 自定义配置会被优先输出 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.setFileCreate(new IFileCreate() { @Override public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) { /* // 判断自定义文件夹是否需要创建 checkDir("调用默认方法创建的目录,自定义目录用"); if (fileType == FileType.MAPPER) { // 已经生成 mapper 文件判断存在,不想重新生成返回 false return !new File(filePath).exists(); }*/ // 允许生成模板文件,无论之前代码生成器是否生成过,都重新生成 return true; } }); 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); // 判断是否需要继承父类,从而抽取公共字段 if(scanner("是否需要继承基类?").equalsIgnoreCase("y")){ // 设置父类,解决公共字段冗余 strategy.setSuperEntityClass("com.qbb.simplerightsmanagement.entity.BaseEntity"); // 写于父类中的公共字段 strategy.setSuperEntityColumns("create_time","modified_time","create_account_id","modified_account_id","deleted"); } // 实体类是否使用lombok strategy.setEntityLombokModel(true); // 是否设置Controller为RESTFul风格 strategy.setRestControllerStyle(false); // 公共父类 // strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!"); strategy.setInclude(scanner("表名,多个英文逗号分割").split(",")); // 设置逻辑删除字段 strategy.setLogicDeleteFieldName("deleted"); // 设置自动生成字段策略 ArrayList tableFills = new ArrayList<>(); TableFill createTime = new TableFill("create_time", FieldFill.INSERT); TableFill modifiedTime = new TableFill("modified_time", FieldFill.UPDATE); TableFill createAccountId = new TableFill("create_account_id", FieldFill.INSERT); TableFill modifiedAccountId = new TableFill("modified_account_id", FieldFill.UPDATE); tableFills.add(createTime); tableFills.add(modifiedTime); tableFills.add(createAccountId); tableFills.add(modifiedAccountId); strategy.setTableFillList(tableFills); // Controller的RequestMapping路径是否驼峰 strategy.setControllerMappingHyphenStyle(true); // 表名前缀 // strategy.setTablePrefix(pc.getModuleName() + "_"); mpg.setStrategy(strategy); // 使用什么模板引擎 mpg.setTemplateEngine(new FreemarkerTemplateEngine()); mpg.execute(); } }

基类信息

package com.qbb.simplerightsmanagement.entity;

import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableLogic;
import lombok.Data;

import java.time.LocalDateTime;

/**
 * @author QiuQiu&LL (个人博客:https://www.cnblogs.com/qbbit)
 * @version 1.0
 * @date 2022-02-23  20:29
 * @Description:
 */
@Data
public class BaseEntity {
    /**
     * 创建时间
     */
    @TableField(fill = FieldFill.INSERT)
    private LocalDateTime createTime;

    /**
     * 修改时间
     */
    @TableField(fill = FieldFill.UPDATE)
    private LocalDateTime modifiedTime;

    /**
     * 创建人
     */
    @TableField(fill = FieldFill.INSERT)
    private Long createAccountId;

    /**
     * 修改人
     */
    @TableField(fill = FieldFill.UPDATE)
    private Long modifiedAccountId;

    /**
     * 逻辑删除标识(0、否 1、是)
     */
    @TableLogic
    private Integer deleted;
}

数据库信息

相关