MyBatis 提供 6 大元素構建靈活 SQL:if、choose/when/otherwise、trim、where、set、foreach。底層採用 OGNL 表達式評估條件。
<if> 條件包含若參數為 null,對應片段自動省略,避免手工拼接 SQL 的空格/逗號錯誤。
<choose> / <when> / <otherwise> 互斥分支類似 Java switch-case,只進入第一個滿足條件的 when,全不滿足走 otherwise。
<where> 智能 WHERE 子句WHERE 關鍵字。AND/OR。<trim> 靈活前後綴處理prefix:內容非空時前綴。prefixOverrides:移除內容開頭的指定字串(支援正則管道分隔)。suffix/suffixOverrides:尾部對應功能。<set> 動態 UPDATE 集合UPDATE t_blog WHERE id = #{id} title = #{title}, content = #{content}, owner = #{owner}
SET。if 皆 false,SET 內容為空會報錯,需確保至少一欄更新。<foreach> 集合迭代(IN 條件神器)| 傳入參數類型 | collection 值 | Mapper 簽名範例 |
|---|---|---|
| 單參數 List | list | List<Blog> selectByIds(List<Integer> ids); |
| 單參數 Array | array | List<Blog> selectByIds(Integer[] ids); |
| 多參數 / Map | Map 的 Key 名稱 | List<Blog> selectByIds(@Param("ids") List<Integer> ids); |
<where>、<set>,減少手工維護關鍵字。IN 限制 1000 項,SQL Server 參數上限 2100,超過需分批或用臨時表/TVP。DEBUG 級別),開發期驗證生成 SQL 正確性。