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

使用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!

  • 33
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
如何使用? 很高兴为您解答这个问题。为了使用MyBatis-Plus自动生成代码模板Controller,您需要遵循以下步骤: 1. 安装MyBatis-Plus插件。您可以在Maven中添加以下代码来添加MyBatis-Plus依赖项: ```xml <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.1</version> </dependency> ``` 2. 根据您的需要配置MyBatis-Plus。您可以在application.properties文件中添加以下配置: ```properties # 数据库连接 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://your-database-url:3306/your-database-name?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=UTC spring.datasource.username=your-database-username spring.datasource.password=your-database-password # MyBatis-Plus配置 mybatis-plus.mapper-locations=classpath:mapper/*.xml mybatis-plus.type-aliases-package=com.example.demo.entity ``` 3. 在您的实体类中添加需要映射的数据库表。对于每个表,需要创建一个Java类,用于映射表中的数据。您可以使用MyBatis-Plus提供的注解来配置主键和字段的映射: ```java @Data @TableName("user") // 表名 public class User { @TableId(value = "id", type = IdType.AUTO) // 主键 private Long id; @TableField("name") // 字段 private String name; // 省略其他字段 } ``` 4. 使用MyBatis-Plus代码生成生成代码MyBatis-Plus提供了一个代码生成器,该生成器可以根据您的实体类和数据库表自动生成代码。您可以使用以下命令启动代码生成器: ```java import com.baomidou.mybatisplus.generator.AutoGenerator; public class CodeGenerator { public static void main(String[] args) { AutoGenerator mpg = new AutoGenerator(); // 定义包名和文件路径 // ... // 配置数据源 // ... // 配置生成策略 // ... // 配置模板 // ... mpg.execute(); } } ``` 5. 完成后,您将在指定的文件夹中看到生成代码,包括实体类、Mapper接口、XML文件和Service类。 希望这能帮到您!如果您有任何其他问题,请随时问我。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值