首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 數據庫知識 >  >> DB2 資料庫 >> DB2 教學

MyBatis 核心架構與映射配置完全指南

     編輯:DB2 教學

MyBatis 核心架構與映射配置完全指南

MyBatis 是一款優秀的持久層框架,它支援自定義 SQL、存儲過程以及高級映射。所有 MyBatis 應用程序的核心都是 SqlSessionFactory 實例,而該實例可通過 SqlSessionFactoryBuilder 從 XML 配置文件或 Configuration 類構建而得。

SQL 映射文件的頂級元素

映射文件中的元素必須按照特定順序定義,主要包括:

  • cache:為給定命名空間配置引用緩存。
  • cache-ref:從其他命名空間引用緩存配置。
  • resultMap:描述數據庫結果集與對象之間的對應關系,是最強大的元素。
  • sql:定義可重用的 SQL 代碼塊,可被其他語句引用。
  • insert / update / delete / select:分別映射插入、更新、刪除、查詢語句。

Select 語句關鍵屬性詳解

屬性說明
id命名空間中唯一的標識符,用於引用該語句。
parameterType傳入語句的參數類完全限定名或別名。
resultType返回結果的類型類名或別名;若為集合,則指定集合泛型類型。不可與 resultMap 同時使用。
resultMap引用外部定義的 resultMap。
flushCache設為 true 時調用該語句會清空緩存,默認 false。
useCache設為 true 時結果會被緩存,默認 true。
timeout驅動程序等待數據庫響應的最大時間,默認由驅動處理。
fetchSize建議驅動程序每次批量返回的結果行數。
statementTypeSTATEMENT、PREPARED 或 CALLABLE,默認 PREPARED。
resultSetTypeFORWARD_ONLY、SCROLL_SENSITIVE 或 SCROLL_INSENSITIVE,默認由驅動處理。

Insert 語句專有屬性

  • useGeneratedKeys:啟用 JDBC getGeneratedKeys 獲取數據庫自增主鍵,默認 false。
  • keyProperty:標記屬性以接收生成的鍵值,可配合 selectKey 使用。

動態 SQL:基於 OGNL 表達式的強大功能

MyBatis 的動態 SQL 通過以下元素實現靈活的 SQL 構建:

  • if:簡單條件判斷,實現可選條件拼接。
  • choose / when / otherwise:類似 Java 的 switch 語句,單選分支。
  • trim:靈活添加/移除前後綴,可替代 where/set 元素。屬性包括 prefix、suffix、prefixOverrides、suffixOverrides。
  • where:智能處理 WHERE 子句,自動去除首個 AND/OR。
  • set:用於更新操作,自動添加 SET 關鍵字並去除尾部逗號。
  • foreach:遍歷集合構建 IN 條件等。關鍵屬性:item(別名)、index(索引)、collection(集合)、open/separator/close(分隔符)。
    collection 值規則:單參數 List 為 "list",數組為 "array",多參數時為 Map 中的 key。

關聯查詢:Association 與 Collection

Association(一對一)

處理一對一關系,需指定 Java 實體屬性、javaType、數據庫列名。兩種加載方式:

  1. select:執行另一條映射 SQL 返回實體,較靈活。
  2. resultMap:使用嵌套結果映射處理 JOIN 查詢結果。

Collection(一對多)

處理一對多關系,需指定屬性、javaType(通常為 ArrayList)、ofType(泛型類型)、列名。同樣支援 select 和 resultMap 兩種加載策略。

resultMap 子元素速查

  • constructor:通過構造器注入結果;包含 idArg(標記 ID)和 arg(普通注入)。
  • id:結果集唯一標識,利於緩存與引用。
  • result:注入普通字段或 JavaBean 屬性。
  • association:複雜類型關聯,支援嵌套結果映射與外部引用。
  • collection:複雜類型集合,支援嵌套與引用。
  • discriminator:根據結果值決定使用哪個 resultMap;包含 case 子元素。

id / result 通用屬性

屬性說明
property映射的字段或屬性名,支援點號路徑如 address.street.number。
column數據庫列名或別名,對應 resultSet.getString(columnName)。
javaType完整類名或別名;映射 HashMap 時需顯式指定。
jdbcType針對可空列在 INSERT/UPDATE/DELETE 時指定 JDBC 類型。
typeHandler覆蓋默認類型處理器,值為實現類全限定名或別名。

實戰映射文件示例

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.study.mybatis.StudyMybatis">
  <typeAlias type="com.study.mybatis.model.StudyMybatis" alias="StudyMybatisMap"/>
  <resultMap type="StudyMybatisMap" id="selectStudyMybatis">
    <id property="id" column="studymybatis_id"/>
    <result property="name" column="studymybatis_name"/>
    <result property="password" column="studymybatis_password"/>
    <result property="phone" column="studymybatis_phone"/>
    <result property="classid" column="studymybatis_classid"/>
  </resultMap>

  <select id="selectByid" resultMap="selectStudyMybatis" parameterType="int">
    select studymybatis_id,studymybatis_name,studymybatis_password,studymybatis_phone
    from studymybatis where id=#{id}
  </select>

  <!-- trim 動態 WHERE 示例 -->
  <select id="selectByExample" resultMap="selectStudyMybatis" parameterType="java.util.Map">
    select studymybatis_id,studymybatis_name,studymybatis_password,studymybatis_phone
    from studymybatis sm
    <trim prefix="where" prefixOverrides="AND | OR">
      <if test="studymybatis_name !=null and studymybatis_name!=''">
        and sm.studymybatis_name = #{name}
      </if>
      <if test="classid != null and classid != ''">
        and sm.studymybatis_classid=#{classid}
      </if>
    </trim>
  </select>

  <!-- 級聯查詢:association + select -->
  <resultMap type="com.study.mybatis.model.StudyMybatis" id="studySelect">
    <id property="id" column="studymybatis_id"/>
    <result property="name" column="studymybatis_name"/>
    <association property="cid" column="classid" javaType="com.study.mybatis.StudyClass" select="classSelect"/>
  </resultMap>
  <select id="selectStudy" resultMap="studySelect" parameterType="java.math.BigDecimal">
    select * from studymybatis where studymybatis_id=#{id}
  </select>
  <select id="selectClass" resultMap="classSelect" parameterType="java.math.BigDecimal">
    select * from studyclass where classid=#{cid}
  </select>

  <!-- 聚合查詢:collection -->
  <resultMap type="com.study.mybatis.model.StudyClass" id="classResultMap">
    <id property="id" column="classid"/>
    <result property="classage" column="classage"/>
    <result property="banji" column="banji"/>
    <collection property="studymybatisList" column="classid" javaType="ArrayList" ofType="StudyMybatis" resultMap="com.study.mybatis.model.StudyMybatis"/>
  </resultMap>
  <select id="classandmybatis" parameterType="int" resultMap="classResultMap">
    select * from studyclass sc left outer join studymybatis sm on sc.classid=sm.studymybatis_classid where sc.banji=${banji}
  </select>
</mapper>
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved