mybatis-plus自动生成代码(详细配置)

本文详细介绍了如何在SpringBoot项目中使用mybatis-plus进行数据库连接配置和代码自动生成,包括添加相关Maven依赖、配置生成器、指定表名和自定义模板,适用于独立模块和聚合模块。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用mybatis-plus自动生成代码是开发过程中提效必不可少的,下面就一起来详细的配置自动生成代码的过程

创建maven项目

img

添加依赖

<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>

  <!--lombok依赖-->
  <dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
  </dependency>

  <!--mysql依赖-->
  <dependency>
    <groupId>com.mysql</groupId>
    <artifactId>mysql-connector-j</artifactId>
    <scope>runtime</scope>
  </dependency>

  <!--mybatis-plus依赖-->
  <dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.4.2</version>
  </dependency>

  <!-- 代码自动生成器依赖-->
  <dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-generator</artifactId>
    <version>3.4.1</version>
  </dependency>

  <!-- 代码自动生成模版依赖-->
  <dependency>
    <groupId>org.apache.velocity</groupId>
    <artifactId>velocity-engine-core</artifactId>
    <version>2.3</version>
  </dependency>

  <!--添加Knife4j依赖-->
  <dependency>
    <groupId>com.github.xiaoymin</groupId>
    <artifactId>knife4j-openapi2-spring-boot-starter</artifactId>
    <version>4.1.0</version>
  </dependency>

  <!--分页插件依赖-->
  <dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper-spring-boot-starter</artifactId>
    <version>1.4.1</version>
  </dependency>

</dependencies>

依赖说明

连接数据库相关: mysql依赖、mybatis-plus依赖

自动生成代码相关:代码自动生成模版依赖、代码自动生成器依赖

其他依赖:分页插件依赖、Knife4j依赖、lombok依赖

项目结构

一般项目结构有两种:

  1. 独立模块
  2. 聚合模块
独立模块

独立模块目录如下,没有第二层机构

img

聚合模块

聚合模块目录如下,有第二层机构,包底下细分user、order、product模块

img

代码自动生成配置

1. test中新建CodeGenerator类

img

2. 添加配置的代码
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.*;
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 org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

/**
 * @author csn
 * @date 2023/4/4
 */

public class CodeGenerator {

    // 数据库链接
    private static final String DATABASE_URL = "jdbc:mysql://localhost:3306/security?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8";
    // 数据库用户名
    private static final String DATABASE_USERNAME = "root";
    // 数据库密码
    private static final String DATABASE_PASSWORD = "12345678";
    // 包名(根据自己项目修改)
    private static final String PACKAGE_NAME = "com.mamba.codegenerator";
    // 模块名称(如果项目中有多个模块需要设置(如:用户模块、商品模块、订单模块),只有一个模块就不用设置(为空就好))
    private static final String SECOND_MODULE = "user";
    // 作者
    private static final String AUTHOR = "csn";
    // 表前缀(org_user表需要去掉前缀时这里填写"org_")
    private static final String TABLE_PREFIX = "";
    // 生成代码文件的路径
    private static final String PARENT = PACKAGE_NAME + (StringUtils.isNotBlank(SECOND_MODULE) ? "." + SECOND_MODULE : "");
    // 生成xml文件的路径
    private static final String XML_PATH = "/src/main/resources/mapper" + (StringUtils.isNotBlank(SECOND_MODULE) ? "/" + SECOND_MODULE : "");

    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.setFileOverride(true);
        // 是否打开生成目录
        gc.setOpen(false);
        // 设置项目作者名称
        gc.setAuthor(AUTHOR);
        // 设置主键策略
        gc.setIdType(IdType.AUTO);
        // 生成基本ResultMap
        gc.setBaseResultMap(true);
        // 生成基本ColumnList
        gc.setBaseColumnList(true);
        // 去掉服务默认前缀
        gc.setServiceName("%sService");
        // 设置时间类型
        gc.setDateType(DateType.ONLY_DATE);
        // 设置Swagger2
        gc.setSwagger2(true);
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        // 数据库链接
        dsc.setUrl(DATABASE_URL);
        // 数据库驱动
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        // 数据库用户名
        dsc.setUsername(DATABASE_USERNAME);
        // 数据库密码
        dsc.setPassword(DATABASE_PASSWORD);
        mpg.setDataSource(dsc);

        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setParent(PARENT);
        pc.setMapper("mapper");
        pc.setXml("mapper");
        pc.setEntity("entity");
        pc.setService("service");
        pc.setServiceImpl("service.impl");
        pc.setController("controller");
        Map<String, String> packageInfo = new HashMap<>();
        String path = gc.getOutputDir() + PARENT.replace(".", "/") + "/";
        String xmlPath = projectPath + XML_PATH;
        System.out.println("XML_PATH:" + xmlPath);
        packageInfo.put(ConstVal.XML_PATH, xmlPath);
        packageInfo.put(ConstVal.ENTITY_PATH, path + "entity");
        packageInfo.put(ConstVal.SERVICE_PATH, path + "service");
        packageInfo.put(ConstVal.SERVICE_IMPL_PATH, path + "service/impl");
        packageInfo.put(ConstVal.MAPPER_PATH, path + "mapper");
        packageInfo.put(ConstVal.CONTROLLER_PATH, path + "controller");
        pc.setPathInfo(packageInfo);
        mpg.setPackageInfo(pc);

        // 策略配置
        StrategyConfig sc = new StrategyConfig();
        sc.setNaming(NamingStrategy.underline_to_camel);
        sc.setColumnNaming(NamingStrategy.underline_to_camel);
        // 自动lombok
        sc.setEntityLombokModel(true);
        sc.setRestControllerStyle(true);
        sc.setControllerMappingHyphenStyle(true);
        // 设置逻辑删除
        sc.setLogicDeleteFieldName("deleted");

        // 设置自动填充配置
        TableFill gmt_create = new TableFill("create_time", FieldFill.INSERT);
        TableFill gmt_modified = new TableFill("update_time", FieldFill.INSERT_UPDATE);
        ArrayList<TableFill> tableFills = new ArrayList<>();
        tableFills.add(gmt_create);
        tableFills.add(gmt_modified);
        sc.setTableFillList(tableFills);

        // 乐观锁
        sc.setVersionFieldName("version");
        // 驼峰命名
        sc.setRestControllerStyle(true);

        // 设置表名前缀
        sc.setTablePrefix(TABLE_PREFIX);
        // 设置需要生成的表名
        sc.setInclude(scanner("表名,如果同时输入多个表名,中间用英文逗号分割(例如:user,order,product)").split(","));
        mpg.setStrategy(sc);

        // 自定义配置模板
        TemplateConfig templateConfig = new TemplateConfig();
        templateConfig.setController("templates/controller.java");
        mpg.setTemplate(templateConfig);

        // 生成代码
        mpg.execute();

    }

    public static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入" + tip + ":");
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StringUtils.isNotBlank(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("请输入正确的" + tip + "!");
    }


}
3. 自定义模块

一般自动生成的文件可能不是自己想要的,这时候就要自定义模版了

这里自定义了controller类的模版controller.java.vm

img

具体代码如下

package ${package.Controller};


import ${package.Service}.${table.serviceName};
import ${package.Entity}.${entity};
#if(${restControllerStyle})
import org.springframework.web.bind.annotation.RestController;
#else
import org.springframework.stereotype.Controller;
#end
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.HttpStatus;
import com.github.pagehelper.PageHelper;
import java.util.List;
import org.springframework.http.ResponseEntity;

/**
 *
 * @author ${author}
 * @since ${date}
 */
#if(${restControllerStyle})
@RestController
#else
@Controller
#end
@Api(tags = "${table.comment}管理")
public class ${table.controllerName} {

    @Resource
    private ${table.serviceName} ${table.entityPath}Service;

    @ApiOperation("${table.comment}-添加")
    @PostMapping("/${table.entityPath}")
    public ResponseEntity<${entity}> add(@RequestBody ${entity} ${table.entityPath}){
        ${table.entityPath}Service.save(${table.entityPath});
        return ResponseEntity.status(HttpStatus.CREATED).body(${table.entityPath}Service.getById(${table.entityPath}.getId()));
    }

    @ApiOperation("${table.comment}-删除")
    @DeleteMapping("/${table.entityPath}/{id}" )
    public Boolean delete(@PathVariable Integer id){
        ${table.entityPath}Service.removeById(id);
        return true;
    }

    @ApiOperation("${table.comment}-修改")
    @PutMapping("/${table.entityPath}/{id}" )
    public ${entity} update(@PathVariable Integer id,@RequestBody ${entity} ${table.entityPath}){
        ${table.entityPath}Service.updateById(${table.entityPath});
        return ${table.entityPath}Service.getById(id);
    }

    @ApiOperation("${table.comment}-详情")
    @GetMapping("/${table.entityPath}/{id}" )
    public ${entity} detail(@PathVariable Integer id){
        return ${table.entityPath}Service.getById(id);
    }

    @ApiOperation("${table.comment}-列表")
    @GetMapping("/${table.entityPath}" )
    public PageInfo<${entity}> list(@RequestParam(defaultValue = "1") Integer pageIndex,@RequestParam(defaultValue = "10") Integer pageSize){
        PageHelper.startPage(pageIndex,pageSize);
        List<${entity}> list= ${table.entityPath}Service.list();
        return new PageInfo<>(list);
    }

}

自定义模版配置到代码中

// 自定义配置模板
TemplateConfig templateConfig = new TemplateConfig();
templateConfig.setController("templates/controller.java");
mpg.setTemplate(templateConfig);

代码中注释已经很详细了,按着配置就好了

独立模块中SECOND_MODULE留空,聚合模块中SECOND_MODULE写具体的包名

注意:不支持同时生成聚合模块中,不同模块的代码

启动

img

输入要生成的文件的表名

img

按回车即可生成文件

img

大功告成 END!

### MyBatisPlus 自动生成代码插件推荐及使用教程 #### 插件概述 MyBatis-Plus 是一款强大的 MyBatis 增强工具,其内置的代码生成器能够显著提升开发效率。通过该插件,可以快速生成实体类、Mapper 接口及其 XML 文件、Service 接口与其实现类以及 Controller 层代码[^2]。 --- #### 插件安装方法 在 IntelliJ IDEA 中安装 MyBatis-Plus 插件的过程如下: 1. 打开 IDE 设置窗口:`File -> Settings...` 2. 转到 `Plugins` 部分,在 Marketplace 或已安装列表中搜索 “MybatisPlus”。 3. 如果未找到官方插件,则可以通过手动下载 JAR 包的方式将其作为第三方插件引入[^3]。 --- #### 数据库连接配置 为了使代码生成器正常工作,需先完成数据库连接设置。具体步骤包括但不限于以下内容: - 创建一个新的数据源或者编辑现有的 JDBC URL、用户名和密码字段。 - 测试连接以确认参数无误[^1]。 --- #### 代码生成流程 以下是利用 MyBatis-Plus 实现自动化编码的主要环节: ##### 1. 初始化模板引擎 定义全局属性(如作者名、日期格式化样式),指定包路径结构以便于后续分类管理生成后的文件[^4]。 ```java // 示例代码展示如何初始化 GeneratorConfig 对象 AutoGenerator mpg = new AutoGenerator(); mpg.setGlobalConfig(new GlobalConfig() .setAuthor("Your Name") // 设定代码创建者名称 .setOutputDir(System.getProperty("user.dir"))); // 输出目录位置 ``` ##### 2. 映射表至 Java 类型 指明待处理的数据表格名称或模式匹配规则;支持单张表单独转换成对象形式亦可批量操作多张关联表。 ```java DataSourceConfig dsc = new DataSourceConfig(); dsc.setUrl("jdbc:mysql://localhost:3306/your_database"); dsc.setUsername("root"); dsc.setPassword("password"); mpg.setDataSource(dsc); ``` ##### 3. 启动构建过程 执行最终命令触发整个流水线作业链路直至结束输出成果物为止。 ```java mpg.execute(); // 开始生成代码 ``` --- #### 功能特性总结 除了基础 CRUD 方法外,此框架还提供了诸多高级选项来满足不同场景下的定制需求,比如动态 SQL 支持、乐观锁机制嵌入等附加价值服务。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值