首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

MyBatis Mapper 映射配置深度解析:內置方法、XML 解析流程與原理剖析

     編輯:Java 相關知識

Mapper 介面常見內置方法對照表

MyBatis Generator 生成的 Mapper 介面通常包含以下標準方法(以 User 為例):

方法用途對應 SQL 示例
countByExample(example)條件計數SELECT COUNT(*) FROM user WHERE username='joe'
deleteByExample(example)條件批量刪除DELETE FROM user WHERE username='joe'
deleteByPrimaryKey(id)主鍵單條刪除DELETE FROM user WHERE id=101
insert(record)全字段插入INSERT INTO user(id,username,password,email) VALUES(...)
insertSelective(record)非空字段插入僅插入非 null 字段
selectByExample(example)條件查詢列表SELECT * FROM user WHERE username='joe' ORDER BY username
selectByPrimaryKey(id)主鍵查詢單條SELECT * FROM user WHERE id=101
updateByExampleSelective(record, example)條件更新非空字段UPDATE user SET password='123' WHERE username='joe'
updateByExample(record, example)條件更新全字段全字段覆蓋
updateByPrimaryKeySelective(record)主鍵更新非空字段UPDATE user SET password='joe' WHERE id=101
updateByPrimaryKey(record)主鍵更新全字段UPDATE user SET username='joe',password='joe' WHERE id=101

注意:Example 類內部的 Criteria 用於構建 WHERE 條件,支援 andXxxEqualTo、andXxxIsNull、orXxxLike 等豐富條件組合。

Mapper XML 核心元素解析

<mapper namespace="com.example.mapper.UserMapper">
    <!-- 緩存配置 -->
    <cache eviction="LRU" flushInterval="60000" size="512" readOnly="true"/>

    <!-- 結果映射:將查詢列映射到屬性 -->
    <resultMap id="userResultMap" type="User">
        <id property="id" column="id"/>
        <result property="username" column="username"/>
        <result property="email" column="email"/>
        <!-- 關聯對象映射 -->
        <association property="profile" javaType="Profile">
            <id property="id" column="profile_id"/>
            <result property="nickname" column="nickname"/>
        </association>
        <!-- 集合映射 (一對多) -->
        <collection property="articles" ofType="Article">
            <id property="id" column="article_id"/>
            <result property="title" column="title"/>
        </collection>
    </resultMap>

    <!-- 可重用 SQL 片段 -->
    <sql id="userColumns">
        id, username, password, email, create_time
    </sql>

    <select id="selectById" parameterType="int" resultMap="userResultMap">
        SELECT <include refid="userColumns"/> FROM user WHERE id = #{id}
    </select>

    <insert id="insert" parameterType="User" useGeneratedKeys="true" keyProperty="id">
        INSERT INTO user(username, password, email) VALUES(#{username}, #{password}, #{email})
    </insert>

    <update id="updateByPrimaryKeySelective" parameterType="User">
        UPDATE user
        <set>
            <if test="username != null">username = #{username},</if>
            <if test="password != null">password = #{password},</if>
        </set>
        WHERE id = #{id}
    </update>

    <delete id="deleteByPrimaryKey" parameterType="int">
        DELETE FROM user WHERE id = #{id}
    </delete>
</mapper>

MyBatis 解析 Mapper XML 的核心流程(源碼級)

  1. SqlSessionFactoryBean 讀取 mapperLocations 表達式匹配的所有 XML 資源。
  2. 對每個資源創建 XMLMapperBuilder,調用 parse()。
  3. parse() → configurationElement() 依次解析子節點:
    • cache-ref / cache → 緩存配置
    • parameterMap / resultMap → 參數/結果映射
    • sql → SQL 片段註冊
    • select|insert|update|delete → 交由 XMLStatementBuilder 解析為 MappedStatement
  4. MappedStatement 被註冊到 Configuration 的 mappedStatements Map 中,Key 為 namespace + "." + id。
  5. 運行時,SqlSession 根據 Key 獲取 MappedStatement,由 Executor 執行。

關鍵源碼入口

  • XMLMapperBuilder.configurationElement(XNode context):總解析入口。
  • XMLStatementBuilder.parseStatementNode():單條 SQL 節點解析,構建 MappedStatement.Builder。
  • MapperBuilderAssistant.addMappedStatement(...):最終註冊到 Configuration。

最佳實踐提示

  • 盡量使用 resultMap 而非 resultType,支援嵌套映射、列名與屬性名不一致、類型轉換。
  • 動態 SQL 標籤(<if>、<where>、<set>、<foreach>)構建靈活查詢/更新。
  • useGeneratedKeys="true" keyProperty="id" 獲取自增主鍵回填。
  • 大結果集場景啟用 fetchSize、resultSetType="FORWARD_ONLY"、cursor 流式處理。

結語

深入理解 Mapper XML 解析流程與 MappedStatement 註冊機制,有助於排查映射錯誤、優化複雜查詢、擴展自定義語句處理。掌握內置方法語義與動態 SQL 技巧,是高效使用 MyBatis 的關鍵。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved