MyBatis 動態 SQL 基於 OGNL (Object-Graph Navigation Language),支援屬性存取、集合遍歷、方法呼叫等。常用語法:property != null、list.size() > 0、item.id。
<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 條件。
<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。
<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:尾部對應處理
<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>
自動處理:
WHEREAND/OR 開頭 → 自動移除
<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、移除尾部逗號、空內容報錯。
<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 值 | Mapper 介面 |
|---|---|---|
| 單一 List | list | List<Blog> find(@Param("list") List<Integer> ids) |
| 單一 Array | array | List<Blog> find(@Param("array") Integer[] ids) |
| 多參數/Map | Map 中的 key | List<Blog> find(@Param("ids") List<Integer> ids, @Param("name") String name) |
<where> + <if>,最簡潔健壯<foreach> 產生 VALUES (?,?), (?,?)...logImpl=STDOUT_LOGGING)觀察生成 SQL