generatorConfig.xml 配置 Controller、Service 完整教程

generatorConfig.xml 配置 Controller、Service 完整教程

MyBatis Generator(MBG)默认仅生成Entity、Mapper 接口、Mapper XML ,不直接支持 Controller、Service 层的自动生成,核心实现方式是通过自定义代码生成器(继承 MBG 核心类)+ 配置 Velocity 模板来实现,以下是完整可运行的配置和代码实现方案。

一、核心依赖(Maven)

需引入 MBG 核心包、数据库驱动、Velocity 模板引擎(模板渲染)、MyBatis 核心包,以 MySQL 为例,pom.xml 配置如下:

xml

复制代码
<!-- MyBatis Generator 核心依赖 -->
<dependency>
    <groupId>org.mybatis.generator</groupId>
    <artifactId>mybatis-generator-core</artifactId>
    <version>1.4.2</version>
</dependency>
<!-- MySQL 驱动(根据数据库类型替换) -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.33</version>
    <scope>runtime</scope>
</dependency>
<!-- Velocity 模板引擎(渲染 Controller/Service 模板) -->
<dependency>
    <groupId>org.apache.velocity</groupId>
    <artifactId>velocity-engine-core</artifactId>
    <version>2.3</version>
</dependency>
<!-- MyBatis 核心包(基础依赖) -->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.15</version>
</dependency>

二、generatorConfig.xml 核心配置

配置文件放在 src/main/resources 下,核心包含数据库连接、生成规则、包路径、模板路径重点配置自定义 Controller/Service 的生成路径和模板位置,完整配置如下:

xml

复制代码
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

<generatorConfiguration>
    <!-- 1. 配置数据库驱动包路径(本地Maven仓库路径,或绝对路径) -->
    <classPathEntry location="C:\Users\你的用户名\.m2\repository\mysql\mysql-connector-java\8.0.33\mysql-connector-java-8.0.33.jar"/>

    <context id="MySQL" targetRuntime="MyBatis3" defaultModelType="flat">
        <!-- 关闭注释生成 -->
        <commentGenerator>
            <property name="suppressAllComments" value="true"/>
            <property name="suppressDate" value="true"/>
        </commentGenerator>

        <!-- 2. 数据库连接配置(根据实际环境修改) -->
        <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/你的数据库名?useUnicode=true&amp;characterEncoding=utf8&amp;serverTimezone=GMT%2B8&amp;useSSL=false"
                        userId="root"
                        password="你的数据库密码">
        </jdbcConnection>

        <!-- 3. 实体类生成配置 -->
        <javaModelGenerator targetPackage="com.xxx.entity" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>

        <!-- 4. Mapper XML 生成配置 -->
        <sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>

        <!-- 5. Mapper 接口生成配置 -->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.xxx.mapper" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>

        <!-- 6. 自定义 Controller/Service 生成配置(核心) -->
        <!-- targetPackage:生成类的包路径;targetProject:生成目录 -->
        <javaGenerator targetPackage="com.xxx.controller" targetProject="src/main/java" type="CONTROLLER"/>
        <javaGenerator targetPackage="com.xxx.service" targetProject="src/main/java" type="SERVICE"/>
        <javaGenerator targetPackage="com.xxx.service.impl" targetProject="src/main/java" type="SERVICE_IMPL"/>

        <!-- 7. 配置需要生成代码的数据库表(tableName:表名;domainObjectName:实体类名) -->
        <table tableName="user" domainObjectName="User"/>
        <table tableName="order" domainObjectName="Order"/>
        <!-- 更多表配置... -->

        <!-- 8. 模板路径配置(指向自定义的Velocity模板,相对/绝对路径均可) -->
        <templateConfiguration type="CONTROLLER" location="src/main/resources/template/controller.vm"/>
        <templateConfiguration type="SERVICE" location="src/main/resources/template/service.vm"/>
        <templateConfiguration type="SERVICE_IMPL" location="src/main/resources/template/service-impl.vm"/>
        <!-- 保留MBG默认模板(Entity/Mapper) -->
        <templateConfiguration type="MODEL" location="org/mybatis/generator/templates/model.vm"/>
        <templateConfiguration type="MAPPER" location="org/mybatis/generator/templates/mapper.vm"/>
        <templateConfiguration type="SQLMAP" location="org/mybatis/generator/templates/sqlMap.vm"/>
    </context>
</generatorConfiguration>

配置关键说明

  1. classPathEntry:数据库驱动包的本地绝对路径(需替换为自己的 Maven 仓库路径);
  2. jdbcConnection:替换为实际的数据库地址、用户名、密码(MySQL8.0 + 驱动类为com.mysql.cj.jdbc.Driver,5.x 为com.mysql.jdbc.Driver);
  3. 包路径:将com.xxx替换为自己的项目包名(如com.demo);
  4. 表配置:tableName为数据库真实表名,domainObjectName为生成的实体类名(首字母大写,驼峰命名);
  5. 模板路径:location指向自定义模板的存放位置,下文会提供模板示例。

三、自定义 Velocity 模板(Controller/Service/ServiceImpl)

src/main/resources 下创建 template 目录,新建 3 个 Velocity 模板文件,模板中通过$table$domainObjectName等变量获取表和实体信息,适配 MBG 的上下文参数。

1. Controller 模板:src/main/resources/template/controller.vm

生成基础的 RESTful 接口,自动注入 Service,包含增删改查基础方法:

vm

复制代码
package $targetPackage;

import com.xxx.entity.$domainObjectName;
import com.xxx.service.$domainObjectNameService;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;

/**
 * $domainObjectName 控制器
 * 自动生成:MyBatis Generator 自定义扩展
 */
@RestController
@RequestMapping("/$tableName")
public class ${domainObjectName}Controller {

    @Resource
    private ${domainObjectName}Service $domainObjectName.toLowerCase()Service;

    /**
     * 根据ID查询
     */
    @GetMapping("/{id}")
    public $domainObjectName getById(@PathVariable Long id) {
        return $domainObjectName.toLowerCase()Service.getById(id);
    }

    /**
     * 新增
     */
    @PostMapping
    public boolean save(@RequestBody $domainObjectName entity) {
        return $domainObjectName.toLowerCase()Service.save(entity);
    }

    /**
     * 修改
     */
    @PutMapping
    public boolean update(@RequestBody $domainObjectName entity) {
        return $domainObjectName.toLowerCase()Service.update(entity);
    }

    /**
     * 根据ID删除
     */
    @DeleteMapping("/{id}")
    public boolean delete(@PathVariable Long id) {
        return $domainObjectName.toLowerCase()Service.delete(id);
    }

    /**
     * 查询所有
     */
    @GetMapping
    public List<$domainObjectName> list() {
        return $domainObjectName.toLowerCase()Service.list();
    }
}

2. Service 接口模板:src/main/resources/template/service.vm

生成基础的业务层接口,定义增删改查方法:

vm

复制代码
package $targetPackage;

import com.xxx.entity.$domainObjectName;
import java.util.List;

/**
 * $domainObjectName 业务层接口
 * 自动生成:MyBatis Generator 自定义扩展
 */
public interface ${domainObjectName}Service {

    /**
     * 根据ID查询实体
     */
    $domainObjectName getById(Long id);

    /**
     * 新增实体
     */
    boolean save($domainObjectName entity);

    /**
     * 修改实体
     */
    boolean update($domainObjectName entity);

    /**
     * 根据ID删除
     */
    boolean delete(Long id);

    /**
     * 查询所有实体
     */
    List<$domainObjectName> list();
}

3. ServiceImpl 实现类模板:src/main/resources/template/service-impl.vm

实现 Service 接口,自动注入 Mapper,调用 Mapper 层方法:

vm

复制代码
package $targetPackage;

import com.xxx.entity.$domainObjectName;
import com.xxx.mapper.${domainObjectName}Mapper;
import com.xxx.service.${domainObjectName}Service;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;

/**
 * $domainObjectName 业务层实现类
 * 自动生成:MyBatis Generator 自定义扩展
 */
@Service
public class ${domainObjectName}ServiceImpl implements ${domainObjectName}Service {

    @Resource
    private ${domainObjectName}Mapper $domainObjectName.toLowerCase()Mapper;

    @Override
    public $domainObjectName getById(Long id) {
        return $domainObjectName.toLowerCase()Mapper.selectByPrimaryKey(id);
    }

    @Override
    public boolean save($domainObjectName entity) {
        return $domainObjectName.toLowerCase()Mapper.insertSelective(entity) > 0;
    }

    @Override
    public boolean update($domainObjectName entity) {
        return $domainObjectName.toLowerCase()Mapper.updateByPrimaryKeySelective(entity) > 0;
    }

    @Override
    public boolean delete(Long id) {
        return $domainObjectName.toLowerCase()Mapper.deleteByPrimaryKey(id) > 0;
    }

    @Override
    public List<$domainObjectName> list() {
        return $domainObjectName.toLowerCase()Mapper.selectAll();
    }
}

模板变量说明

  • $targetPackage:对应generatorConfig.xmljavaGeneratortargetPackage(生成类的包路径);
  • $domainObjectName:表对应的实体类名(如User);
  • $tableName:数据库表名(如user);
  • 所有 Mapper 方法为 MBG 默认生成的方法(selectByPrimaryKeyinsertSelective等),无需手动定义。

四、自定义 MBG 代码生成器(核心 Java 类)

MBG 默认无 Controller/Service 生成逻辑,需继承org.mybatis.generator.api.ShellCallback和实现org.mybatis.generator.api.JavaGenerator,自定义生成逻辑,读取 Velocity 模板并渲染生成 Java 文件。

创建生成器主类 src/main/java/com/xxx/generator/MyBatisGeneratorExt.java

java

运行

复制代码
package com.xxx.generator;

import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.mybatis.generator.api.*;
import org.mybatis.generator.config.*;
import org.mybatis.generator.internal.DefaultShellCallback;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * 自定义MyBatis Generator扩展,支持Controller/Service/ServiceImpl生成
 */
public class MyBatisGeneratorExt {

    static {
        // 初始化Velocity模板引擎
        Properties prop = new Properties();
        prop.setProperty(Velocity.ENCODING_DEFAULT, "UTF-8");
        prop.setProperty(Velocity.OUTPUT_ENCODING, "UTF-8");
        prop.setProperty(Velocity.RESOURCE_LOADER, "file");
        Velocity.init(prop);
    }

    public static void main(String[] args) throws Exception {
        // 1. 配置MBG核心参数
        List<String> warnings = new ArrayList<>();
        boolean overwrite = true; // 覆盖已存在的生成文件
        File configFile = new File("src/main/resources/generatorConfig.xml"); // 配置文件路径

        // 2. 加载配置文件
        ConfigurationParser cp = new ConfigurationParser(warnings);
        Configuration config = cp.parseConfiguration(configFile);

        // 3. 初始化回调(处理文件生成)
        ShellCallback callback = new DefaultShellCallback(overwrite);
        org.mybatis.generator.api.MyBatisGenerator generator = new org.mybatis.generator.api.MyBatisGenerator(config, callback, warnings);

        // 4. 执行默认生成(Entity/Mapper/XML)
        generator.generate(null);

        // 5. 执行自定义生成(Controller/Service/ServiceImpl)
        generateCustomCode(config);

        // 打印生成结果
        for (String warning : warnings) {
            System.out.println("警告:" + warning);
        }
        System.out.println("代码生成完成!");
    }

    /**
     * 自定义生成逻辑:渲染Velocity模板,生成Controller/Service/ServiceImpl
     */
    private static void generateCustomCode(Configuration config) throws Exception {
        Context context = config.getContexts().get(0);
        List<TableConfiguration> tables = context.getTableConfigurations();

        // 遍历所有配置的表,逐个生成代码
        for (TableConfiguration table : tables) {
            String domainObjectName = table.getDomainObjectName(); // 实体类名(如User)
            String tableName = table.getTableName(); // 数据库表名(如user)

            // 遍历所有自定义Java生成配置(Controller/Service/ServiceImpl)
            for (JavaGeneratorConfiguration javaGenConfig : context.getJavaGeneratorConfigurations()) {
                String type = javaGenConfig.getType(); // 生成类型(CONTROLLER/SERVICE/SERVICE_IMPL)
                String targetPackage = javaGenConfig.getTargetPackage(); // 目标包名
                String targetProject = javaGenConfig.getTargetProject(); // 目标目录

                // 获取对应模板配置
                TemplateConfiguration templateConfig = context.getTemplateConfigurations().stream()
                        .filter(t -> type.equals(t.getType()))
                        .findFirst()
                        .orElseThrow(() -> new Exception("未找到" + type + "对应的模板配置"));

                // 1. 构建Velocity上下文(传递模板变量)
                VelocityContext velocityContext = new VelocityContext();
                velocityContext.put("domainObjectName", domainObjectName);
                velocityContext.put("tableName", tableName);
                velocityContext.put("targetPackage", targetPackage);
                velocityContext.put("lowerCaseName", domainObjectName.substring(0, 1).toLowerCase() + domainObjectName.substring(1)); // 首字母小写的实体名

                // 2. 构建生成文件的全路径
                String className = getClassNameByType(domainObjectName, type);
                String packagePath = targetPackage.replace(".", File.separator);
                File targetDir = new File(targetProject + File.separator + packagePath);
                if (!targetDir.exists()) {
                    targetDir.mkdirs(); // 自动创建多级目录
                }
                File targetFile = new File(targetDir, className + ".java");

                // 3. 渲染模板并写入文件
                try (Writer writer = new OutputStreamWriter(new FileOutputStream(targetFile), StandardCharsets.UTF_8)) {
                    Velocity.mergeTemplate(templateConfig.getLocation(), "UTF-8", velocityContext, writer);
                }
            }
        }
    }

    /**
     * 根据生成类型获取类名(如User + CONTROLLER → UserController)
     */
    private static String getClassNameByType(String domainObjectName, String type) {
        return switch (type) {
            case "CONTROLLER" -> domainObjectName + "Controller";
            case "SERVICE" -> domainObjectName + "Service";
            case "SERVICE_IMPL" -> domainObjectName + "ServiceImpl";
            default -> domainObjectName;
        };
    }
}

五、代码生成执行步骤

  1. 配置检查 :确认generatorConfig.xml中的数据库连接、包路径、表配置、模板路径均正确;
  2. 模板创建 :确保template目录下的 3 个 Velocity 模板已创建,无语法错误;
  3. 运行生成器 :直接运行MyBatisGeneratorExt类的main方法;
  4. 结果验证 :生成完成后,在src/main/java对应包下会看到:
    • com.xxx.entity:实体类(MBG 默认生成);
    • com.xxx.mapper:Mapper 接口 + XML(MBG 默认生成);
    • com.xxx.controller:控制器类(自定义生成);
    • com.xxx.service:Service 接口(自定义生成);
    • com.xxx.service.impl:Service 实现类(自定义生成)。

六、关键注意事项

  1. 驱动包路径classPathEntrylocation必须是本地绝对路径,否则 MBG 无法加载数据库驱动;
  2. 包名替换 :所有模板和配置中的com.xxx需统一替换为项目实际包名,否则会出现类导入错误;
  3. 表主键 :MBG 默认生成的selectByPrimaryKeydeleteByPrimaryKey等方法依赖表的主键,需确保配置的表已设置主键;
  4. 文件覆盖 :生成器中overwrite = true表示覆盖已存在的生成文件,开发中若手动修改过生成类,建议改为false避免覆盖;
  5. Velocity 语法 :模板中变量使用$变量名,代码块无需额外标记,确保模板中 Java 语法正确(如包导入、方法定义)。

七、扩展优化(可选)

  1. 添加分页支持 :在 Service/Controller 中添加分页方法,模板中引入分页参数(如PageInfoPageParam);
  2. 自定义方法:在模板中添加业务自定义方法(如按条件查询、批量操作);
  3. 异常处理 :在 Controller 中添加全局异常捕获(@RestControllerAdvice),Service 中抛出业务异常;
  4. 多模块适配 :若为多模块项目,将targetProject改为模块目录(如../service/src/main/java);
  5. 注解优化 :在 Controller 中添加@Api(Swagger)、@Valid(参数校验)等注解,提升接口规范性。

以上配置为通用可运行方案,适配绝大多数 Spring Boot + MyBatis 项目,只需根据实际环境修改少量配置即可直接使用。

相关推荐
tb_first4 小时前
万字超详细苍穹外卖学习笔记1
java·jvm·spring boot·笔记·学习·tomcat·mybatis
老毛肚6 小时前
Orm框架的发展历史与mybatis的高级应用 01
mybatis
特立独行的猫a9 小时前
从XML到Compose的UI变革:现代(2026)Android开发指南
android·xml·ui·compose·jetpack
lbb 小魔仙12 小时前
MyBatis-Plus 系统化实战:从基础 CRUD 到高级查询与性能优化
java·性能优化·mybatis
spencer_tseng15 小时前
Stream not available [SysDictDataMapper.xml]
xml·java
tb_first1 天前
SSM速通3
java·jvm·spring boot·mybatis
tb_first1 天前
SSM速通4
java·jvm·spring·tomcat·maven·mybatis
程可爱1 天前
springboot整合mybatis和postgresql
spring boot·postgresql·mybatis
risc1234561 天前
【Elasticsearch】LeafDocLookup 详述
大数据·elasticsearch·mybatis