MyBatis 動態 SQL 基於 OGNL 表達式,解決 SQL 拼接、條件判斷、迭代等痛點,主要標籤:
<if>:條件判斷<choose>、<when>、<otherwise>:多條件互斥選擇<trim>:靈活處理前綴/後綴(替代 where/set)<where>:智能處理 WHERE 子句(自動去除首個 AND/OR)<set>:智能處理 UPDATE 的 SET 子句(自動去除尾部逗號)<foreach>:集合迭代(批次新增、IN 查詢)<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>
<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>
<insert id="batchInsert">
INSERT INTO user (username, email, status) VALUES
<foreach collection="list" item="user" separator=",">
(#{user.username}, #{user.email}, #{user.status})
</foreach>
</insert>
<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>
<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>。<foreach>,避免循環執行單條 SQL 造成效能問題。collection != null and collection.size() > 0。