溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

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. 及時更新生成配置保持與數據庫同步

建議在實際項目中結合具體需求靈活運用本文介紹的技術方案,打造高效穩定的數據訪問層。 “`

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女