MyBatis 作為 Java 持久層框架的佼佼者,其強大的動態 SQL 功能讓開發者擺脫了傳統 JDBC 中拼接 SQL 字符串的痛苦。本文將深入淺出地講解 MyBatis 中四大核心動態 SQL 標籤——<if>、<choose/when/otherwise>、<where/trim> 以及 <foreach> 的實戰用法,幫助你構建靈活、可維護的數據庫查詢邏輯。
<if> 是最常用的動態 SQL 元素,根據傳入參數的條件決定是否包含特定 SQL 片段。例如分頁查詢場景:
<select id="getListByPagenate" parameterType="PagenateArgs" resultType="Visitor">
select * from (
<include refid="getListSql" />
<include refid="orderBySql"/>
) t
<if test="pageStart > -1 and pageSize > -1">
limit #{pageStart}, #{pageSize}
</if>
</select>
<sql id="getListSql">
select * from Visitor where status > 0
</sql>
<sql id="orderBySql">
order by ${orderFieldStr} ${orderDirectionStr}
</sql>
關鍵提示: 在 OGNL 表達式中使用 and 而非 &&,否則配置文件無法識別。
當多個條件僅需滿足其中一個時,<choose> 類似 Java 的 switch-case 結構。以下示例根據傳入參數優先按 ID、名稱或創建時間查詢:
<select id="getListChooseWhenDemo" resultMap="visitorRs" parameterType="BasicQueryArgs">
<include refid="getListSqlConditions" />
<where>
<if test="queryStatus > 0"> status=#{queryStatus} </if>
<choose>
<when test="queryId != 0"> and id=#{queryId} </when>
<when test="queryName != null"> and name like #{queryName} </when>
<otherwise> and createTime >= #{queryTime} </otherwise>
</choose>
</where>
</select>
<where> 標籤會自動處理 AND/OR 關鍵字的前綴問題,避免出現 WHERE AND ... 這類語法錯誤:
<select id="getListWhereDemo" resultMap="visitorRs" parameterType="BasicQueryArgs">
<include refid="getListSqlConditions" />
<where>
<if test="queryStatus > 0"> status > 0 </if>
<if test="queryId > 0"> and id=#{queryId} </if>
<if test="queryName != null"> and name like #{queryName} </if>
<if test="queryTime != null"> and createTime >= #{queryTime} </if>
</where>
</select>
<trim> 提供更精細的控制,prefix="WHERE" 添加前綴,prefixOverrides="AND |OR " 移除多餘關鍵字。
處理 WHERE id IN (...) 場景時,<foreach> 免去手動拼接字符串的麻煩:
<select id="getListForeachDemo" resultMap="visitorRs">
<include refid="getListSqlConditions"/>
where status > 0 and id in
<foreach collection="list" item="item" index="index" open="(" separator="," close=")">
#{item}
</foreach>
</select>
屬性說明:collection 指定集合參數名(List 用 "list",數組用 "array"),open/close 定義包裹符號,separator 設定分隔符。
MyBatis 基於 OGNL (Object-Graph Navigation Language) 實現動態邏輯。OGNL 支持屬性導航、集合操作、方法調用等強大功能,如 queryName != null and queryName != '' 即為典型 OGNL 表達式。掌握 OGNL 語法能讓你編寫更精準的動態 SQL 條件。
<where> 簡化條件拼接,複雜場景改用 <trim>#{} 參數化輸入防止 SQL 注入,${} 僅用於排序字段等不可參數化場景<sql> 標籤,配合 <include> 復用MyBatis 動態 SQL 將 Java 邏輯與 SQL 結構完美融合,通過 if、choose、where/trim、foreach 四大核心標籤,開發者能輕鬆應對複雜的條件查詢、分頁、批量操作等場景。合理運用這些特性,不僅提升代碼可讀性,更能有效預防 SQL 注入風險,是 MyBatis 進階開發的必備技能。