SpringBoot整合Mybatis Generator自动生成的示例分析

发布时间:2021-08-23 09:15:04 作者:小新
来源:亿速云 阅读:559
# SpringBoot整合Mybatis Generator自动生成的示例分析

## 1. MyBatis Generator简介

### 1.1 核心功能概述
MyBatis Generator(简称MBG)是MyBatis官方提供的代码生成工具,能够根据数据库表结构自动生成以下内容:
- 实体类(POJO)
- Mapper接口
- XML映射文件
- 动态查询条件类(Example类)

### 1.2 典型应用场景
1. **快速开发**:减少70%以上的重复CRUD代码编写
2. **规范统一**:保证项目中的持久层代码风格一致
3. **维护便捷**:表结构变更后重新生成即可同步更新

## 2. 环境准备

### 2.1 基础环境要求
| 组件         | 版本要求       |
|--------------|---------------|
| JDK          | 1.8+          |
| Spring Boot  | 2.3.x+        |
| MyBatis      | 3.5.0+        |
| MySQL        | 5.7+          |

### 2.2 Maven依赖配置
```xml
<dependencies>
    <!-- Spring Boot Starter -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    
    <!-- MyBatis整合Spring Boot -->
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>2.2.0</version>
    </dependency>
    
    <!-- MySQL驱动 -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>
    
    <!-- MyBatis Generator核心 -->
    <dependency>
        <groupId>org.mybatis.generator</groupId>
        <artifactId>mybatis-generator-core</artifactId>
        <version>1.4.1</version>
        <scope>provided</scope>
    </dependency>
</dependencies>

3. 项目配置详解

3.1 数据库连接配置

application.yml 示例:

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/mbg_demo?useSSL=false&serverTimezone=UTC
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver

mybatis:
  mapper-locations: classpath:mapper/*.xml
  type-aliases-package: com.example.mbg.model

3.2 MBG插件配置

pom.xml 中添加构建插件:

<build>
    <plugins>
        <plugin>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-maven-plugin</artifactId>
            <version>1.4.1</version>
            <configuration>
                <configurationFile>src/main/resources/generatorConfig.xml</configurationFile>
                <overwrite>true</overwrite>
            </configuration>
            <dependencies>
                <dependency>
                    <groupId>mysql</groupId>
                    <artifactId>mysql-connector-java</artifactId>
                    <version>8.0.25</version>
                </dependency>
            </dependencies>
        </plugin>
    </plugins>
</build>

4. Generator配置文件解析

4.1 核心配置文件示例

generatorConfig.xml 完整配置:

<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-configuration_1_0.dtd">

<generatorConfiguration>
    <!-- 数据库驱动路径 -->
    <classPathEntry location="/path/to/mysql-connector-java-8.0.25.jar"/>

    <context id="mysqlTables" targetRuntime="MyBatis3">
        <!-- 生成的Java文件编码 -->
        <property name="javaFileEncoding" value="UTF-8"/>
        
        <!-- 自动生成注释配置 -->
        <commentGenerator>
            <property name="suppressDate" value="true"/>
            <property name="suppressAllComments" value="false"/>
        </commentGenerator>

        <!-- 数据库连接配置 -->
        <jdbcConnection 
            driverClass="com.mysql.cj.jdbc.Driver"
            connectionURL="jdbc:mysql://localhost:3306/mbg_demo"
            userId="root"
            password="123456">
        </jdbcConnection>

        <!-- Java模型生成配置 -->
        <javaModelGenerator 
            targetPackage="com.example.mbg.model"
            targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>

        <!-- SQL映射文件生成配置 -->
        <sqlMapGenerator 
            targetPackage="mapper"
            targetProject="src/main/resources">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>

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

        <!-- 表配置 -->
        <table tableName="user_info" domainObjectName="User">
            <generatedKey column="id" sqlStatement="MySQL" identity="true"/>
        </table>
        <table tableName="product">
            <columnOverride column="price" javaType="java.math.BigDecimal"/>
        </table>
    </context>
</generatorConfiguration>

4.2 关键配置项说明

  1. targetRuntime

    • MyBatis3:标准模式(默认)
    • MyBatis3Simple:不生成Example类
  2. table元素属性

    <table 
       tableName="%"               <!-- 匹配所有表 -->
       enableCountByExample="false" <!-- 禁用计数查询 -->
       enableUpdateByExample="false"
       enableDeleteByExample="false"
       selectByExampleQueryId="false">
    
  3. 列级自定义

    <table tableName="employee">
       <columnOverride column="hire_date" property="hireDate" 
           javaType="java.time.LocalDate"/>
       <ignoreColumn column="deleted"/>
    </table>
    

5. 代码生成执行

5.1 命令行执行方式

mvn mybatis-generator:generate

5.2 IDE集成执行(IntelliJ IDEA)

  1. 打开Maven工具窗口
  2. 找到Plugins > mybatis-generator
  3. 双击mybatis-generator:generate目标

5.3 生成结果目录结构

src/
├── main/
│   ├── java/
│   │   └── com/
│   │       └── example/
│   │           └── mbg/
│   │               ├── model/       # 实体类
│   │               └── mapper/      # Mapper接口
│   └── resources/
│       └── mapper/                  # XML映射文件

6. 生成代码分析

6.1 典型实体类示例

public class User {
    private Long id;
    private String username;
    private Integer age;
    private Date createTime;
    
    // getters/setters省略
}

6.2 Mapper接口核心方法

public interface UserMapper {
    int deleteByPrimaryKey(Long id);
    int insert(User record);
    User selectByPrimaryKey(Long id);
    List<User> selectAll();
    int updateByPrimaryKey(User record);
    
    // 动态条件查询
    List<User> selectByExample(UserExample example);
    int updateByExampleSelective(@Param("record") User record, 
                                @Param("example") UserExample example);
}

6.3 XML映射文件片段

<resultMap id="BaseResultMap" type="User">
    <id column="id" property="id" jdbcType="BIGINT"/>
    <result column="username" property="username" jdbcType="VARCHAR"/>
    <result column="age" property="age" jdbcType="INTEGER"/>
</resultMap>

<sql id="Example_Where_Clause">
    <where>
        <foreach collection="oredCriteria" item="criteria" separator="or">
            <if test="criteria.valid">
                <trim prefix="(" suffix=")" prefixOverrides="and">
                    <foreach collection="criteria.criteria" item="criterion">
                        <choose>
                            <when test="criterion.noValue">
                                and ${criterion.condition}
                            </when>
                        </choose>
                    </foreach>
                </trim>
            </if>
        </foreach>
    </where>
</sql>

7. 高级应用技巧

7.1 自定义插件开发

实现PluginAdapter扩展生成逻辑:

public class LombokPlugin extends PluginAdapter {
    @Override
    public boolean modelBaseRecordClassGenerated(TopLevelClass topLevelClass, 
            IntrospectedTable introspectedTable) {
        // 添加Lombok注解
        topLevelClass.addImportedType("lombok.Data");
        topLevelClass.addAnnotation("@Data");
        return true;
    }
}

配置使用插件:

<context id="mysqlTables" targetRuntime="MyBatis3">
    <plugin type="com.example.plugin.LombokPlugin"/>
</context>

7.2 动态条件查询示例

// 创建条件对象
UserExample example = new UserExample();
example.createCriteria()
    .andUsernameLike("%admin%")
    .andAgeBetween(20, 30)
    .andCreateTimeGreaterThan(new Date());

// 排序设置
example.setOrderByClause("create_time DESC");

// 执行查询
List<User> users = userMapper.selectByExample(example);

7.3 分页查询整合

结合PageHelper实现分页:

@GetMapping("/users")
public PageInfo<User> getUsers(@RequestParam(defaultValue = "1") int pageNum,
                              @RequestParam(defaultValue = "10") int pageSize) {
    PageHelper.startPage(pageNum, pageSize);
    UserExample example = new UserExample();
    example.setOrderByClause("id DESC");
    List<User> users = userMapper.selectByExample(example);
    return new PageInfo<>(users);
}

8. 常见问题解决方案

8.1 生成失败排查步骤

  1. 检查数据库连接

    • 确认URL、用户名、密码正确
    • 验证网络可达性
  2. 表名大小写问题

    <table tableName="USER_INFO" delimitIdentifiers="true"/>
    
  3. 日志分析

    • 添加日志配置查看详细错误
    <context id="mysqlTables">
       <property name="logImpl" value="SLF4J"/>
    </context>
    

8.2 字段类型映射优化

自定义类型转换器:

<table tableName="product">
    <columnOverride column="status" 
        javaType="com.example.enums.ProductStatus"
        typeHandler="org.apache.ibatis.type.EnumOrdinalTypeHandler"/>
</table>

8.3 生成代码冲突处理

  1. 部分覆盖策略

    <context id="mysqlTables">
       <property name="mergeable" value="true"/>
    </context>
    
  2. 自定义生成策略

    public class CustomGenerator extends DefaultShellCallback {
       @Override
       public boolean isMergeSupported() {
           return true;
       }
    }
    

9. 性能优化建议

9.1 生成速度优化

  1. 限制生成表的范围
  2. 关闭不需要的插件
  3. 使用批量生成模式

9.2 运行时优化

  1. 启用二级缓存

    <cache eviction="LRU" flushInterval="60000"/>
    
  2. 批量操作示例

    @Insert("<script>insert into user (username) values " +
           "<foreach collection='list' item='item' separator=','>(#{item.username})</foreach></script>")
    void batchInsert(List<User> users);
    

10. 最佳实践总结

  1. 版本控制策略

    • 建议不提交生成的XML文件到版本库
    • 在README中记录生成命令和配置
  2. 项目目录规范

    src/
    ├── generated/       # 生成的代码
    ├── main/           # 手动编写的代码
    └── resources/
       ├── generator/   # MBG配置文件
       └── mapper/     # 自定义SQL片段
    
  3. 持续集成集成

    <plugin>
       <executions>
           <execution>
               <id>generate-mybatis</id>
               <phase>generate-sources</phase>
               <goals>
                   <goal>generate</goal>
               </goals>
           </execution>
       </executions>
    </plugin>
    

结语

通过本文的详细讲解,我们系统性地掌握了Spring Boot与MyBatis Generator的整合方法。合理使用代码生成工具可以显著提升开发效率,但同时需要注意: 1. 生成的代码需要二次审查 2. 复杂查询仍需手动编写SQL 3. 及时更新生成配置保持与数据库同步

建议在实际项目中结合具体需求灵活运用本文介绍的技术方案,打造高效稳定的数据访问层。 “`

推荐阅读:
  1. MyBatis中逆向工程的示例分析
  2. mall整合SpringBoot+MyBatis搭建基本骨架的示例分析

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

springboot mybatis generator

上一篇:C语言自定义类型的示例分析

下一篇:PHP中多字节字符串操作的示例分析

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》