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

MyBatis 動態 SQL 完全指南:trim、where、set、foreach 實戰詳解

     編輯:Java 相關知識

動態 SQL 核心標籤

MyBatis 動態 SQL 基於 OGNL 表達式,解決 SQL 拼接、條件判斷、迭代等痛點,主要標籤:

  • <if>:條件判斷
  • <choose>、<when>、<otherwise>:多條件互斥選擇
  • <trim>:靈活處理前綴/後綴(替代 where/set)
  • <where>:智能處理 WHERE 子句(自動去除首個 AND/OR)
  • <set>:智能處理 UPDATE 的 SET 子句(自動去除尾部逗號)
  • <foreach>:集合迭代(批次新增、IN 查詢)

實戰範例

1. 靈活查詢:條件組合

<select id="findUsers" resultType="User">
    SELECT * FROM user
    <where>
        <if test="username != null and username != ''">
            AND username LIKE CONCAT('%', #{username}, '%')
        </if>
        <if test="status != null">
            AND status = #{status}
        </if>
        <if test="startTime != null and endTime != null">
            AND create_time BETWEEN #{startTime} AND #{endTime}
        </if>
    </where>
    ORDER BY create_time DESC
</select>

2. 動態更新:僅更新非空欄位

<update id="updateUser">
    UPDATE user
    <set>
        <if test="username != null">username = #{username},</if>
        <if test="email != null">email = #{email},</if>
        <if test="status != null">status = #{status}</if>
    </set>
    WHERE id = #{id}
</update>

3. 批次新增:foreach 迭代

<insert id="batchInsert">
    INSERT INTO user (username, email, status) VALUES
    <foreach collection="list" item="user" separator=",">
        (#{user.username}, #{user.email}, #{user.status})
    </foreach>
</insert>

4. trim 進階控制:自定義前後綴

<trim prefix="WHERE" prefixOverrides="AND |OR">
    <if test="name != null">AND name = #{name}</if>
    <if test="age != null">AND age = #{age}</if>
</trim>
<trim prefix="SET" suffixOverrides=",">
    <if test="name != null">name = #{name},</if>
    <if test="age != null">age = #{age},</if>
</trim>

5. selectKey 獲取自增主鍵

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

<insert id="insertUserOracle">
    <selectKey keyProperty="id" resultType="long" order="BEFORE">
        SELECT seq_user.nextval FROM dual
    </selectKey>
    INSERT INTO user (id, username) VALUES (#{id}, #{username})
</insert>

最佳實踐建議

  • 優先使用 <where>、<set> 簡化邏輯,複雜場景用 <trim>。
  • 批次操作(insert/update/delete)必須使用 <foreach>,避免循環執行單條 SQL 造成效能問題。
  • OGNL 表達式中集合判空:collection != null and collection.size() > 0。
  • 動態 SQL 雖強大,但過度複雜會降低可讀性,複雜邏輯建議移至 Service 層或使用存儲過程。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved