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

MyBatis 動態 SQL 完整指南:IF、CHOOSE、TRIM、WHERE、SET、FOREACH 實戰

     編輯:Oracle 教學

OGNL 表達式基礎

MyBatis 動態 SQL 基於 OGNL (Object-Graph Navigation Language),支援屬性存取、集合遍歷、方法呼叫等。常用語法:property != null、list.size() > 0、item.id。

六大核心標籤

1. <if> - 條件包含


<select id="findBlogs" resultType="Blog">
  SELECT * FROM t_blog WHERE 1=1
  <if test="title != null">
    AND title = #{title}
  </if>
  <if test="content != null">
    AND content = #{content}
  </if>
  <if test="owner != null">
    AND owner = #{owner}
  </if>
</select>

若參數為 null 則不生成對應 WHERE 條件。

2. <choose> / <when> / <otherwise> - 互斥分支


<select id="findBlogs" resultType="Blog">
  SELECT * FROM t_blog WHERE 1=1
  <choose>
    <when test="title != null"> AND title = #{title} </when>
    <when test="content != null"> AND content = #{content} </when>
    <otherwise> AND owner = 'owner1' </otherwise>
  </choose>
</select>

類似 Java switch-case,滿足第一個 when 即跳出,否則進入 otherwise。

3. <trim> - 靈活前後綴處理


<select id="findBlogs" resultType="Blog">
  SELECT * FROM t_blog
  <trim prefix="WHERE" prefixOverrides="AND |OR">
    <if test="title != null"> title = #{title} </if>
    <if test="content != null"> AND content = #{content} </if>
    <if test="owner != null"> OR owner = #{owner} </if>
  </trim>
</select>
  • prefix:內容前加關鍵字
  • prefixOverrides:移除內容開頭的關鍵字
  • suffix/suffixOverrides:尾部對應處理

4. <where> - 智慧 WHERE 處理(最常用)


<select id="findBlogs" resultType="Blog">
  SELECT * FROM t_blog
  <where>
    <if test="title != null"> title = #{title} </if>
    <if test="content != null"> AND content = #{content} </if>
    <if test="owner != null"> AND owner = #{owner} </if>
  </where>
</select>

自動處理:

  • 若有條件 → 前加 WHERE
  • 若首條件以 AND/OR 開頭 → 自動移除
  • 若無條件 → 不產生 WHERE

5. <set> - UPDATE 智慧 SET 處理


<update id="updateBlog" parameterType="Blog">
  UPDATE t_blog
  <set>
    <if test="title != null"> title = #{title}, </if>
    <if test="content != null"> content = #{content}, </if>
    <if test="owner != null"> owner = #{owner} </if>
  </set>
  WHERE id = #{id}
</update>

自動處理:前加 SET、移除尾部逗號、空內容報錯。

6. <foreach> - 集合遍歷(IN 查詢、批次 INSERT 必備)


<select id="findByIds" resultType="Blog">
  SELECT * FROM t_blog WHERE id IN
  <foreach collection="list" item="id" index="idx" open="(" separator="," close=")">
    #{id}
  </foreach>
</select>

collection 參數綁定規則

傳入參數collection 值Mapper 介面
單一 ListlistList<Blog> find(@Param("list") List<Integer> ids)
單一 ArrayarrayList<Blog> find(@Param("array") Integer[] ids)
多參數/MapMap 中的 keyList<Blog> find(@Param("ids") List<Integer> ids, @Param("name") String name)

最佳實務建議

  • 動態查詢首選 <where> + <if>,最簡潔健壯
  • 批次插入用 <foreach> 產生 VALUES (?,?), (?,?)...
  • 避免在 SQL 中寫複雜邏輯,必要時移至 Service 層預處理
  • 開啟 MyBatis 日誌(logImpl=STDOUT_LOGGING)觀察生成 SQL
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved