用過 JDBC 或類似框架的人都體會過手動拼接 SQL 的痛苦:既要記得補空格,又要小心去掉列名末尾多餘的逗號。MyBatis 的動態 SQL 正是為了根除這種痛苦而生,它可以嵌入任何 SQL 映射語句中。
動態 SQL 元素的用法與 JSTL 等基於 XML 的文本處理器相似。MyBatis 3 大幅精簡了元素數量,並用基於 OGNL 的強表達式取代其餘:
最常見的場景是有條件地拼接 where 子句的一部分:
<select id="findActiveBlogWithTitleLike" resultType="Blog">
SELECT * FROM BLOG
WHERE state = 'ACTIVE'
<if test="title != null">
AND title like #{title}
</if>
</select>
沒傳 title 時返回所有 ACTIVE 的 BLOG;傳了則做模糊查詢(參數值可包含通配符)。要同時支持 title 與 author 兩個可選條件,只需再加一個 if:
<select id="findActiveBlogLike" resultType="Blog">
SELECT * FROM BLOG WHERE state = 'ACTIVE'
<if test="title != null">
AND title like #{title}
</if>
<if test="author != null and author.name != null">
AND author_name like #{author.name}
</if>
</select>
有些時候只想要「擇一」而非全部生效,choose 有點像 Java 的 switch:
<select id="findActiveBlogLike" resultType="Blog">
SELECT * FROM BLOG WHERE state = 'ACTIVE'
<choose>
<when test="title != null">
AND title like #{title}
</when>
<when test="author != null and author.name != null">
AND author_name like #{author.name}
</when>
<otherwise>
AND featured = 1
</otherwise>
</choose>
</select>
如果把 WHERE 後的第一個條件也做成動態的,麻煩就來了:
<select id="findActiveBlogLike" resultType="Blog">
SELECT * FROM BLOG
WHERE
<if test="state != null">
state = #{state}
</if>
<if test="title != null">
AND title like #{title}
</if>
<if test="author != null and author.name != null">
AND author_name like #{author.name}
</if>
</select>
若一個條件都不匹配,SQL 會變成 SELECT * FROM BLOG WHERE;若只有第二個條件匹配,則變成 WHERE AND title like 'someTitle'——兩種都會執行失敗。
MyBatis 的處理很簡單,用 where 標籤包住即可:
<select id="findActiveBlogLike" resultType="Blog">
SELECT * FROM BLOG
<where>
<if test="state != null">
state = #{state}
</if>
<if test="title != null">
AND title like #{title}
</if>
<if test="author != null and author.name != null">
AND author_name like #{author.name}
</if>
</where>
</select>
where 元素知道只有在至少一個 if 有值時才插入 WHERE,並會自動去掉開頭多餘的 AND 或 OR。若默認行為不合適,可用等價的 trim 自定義:
<trim prefix="WHERE" prefixOverrides="AND |OR "> ... </trim>
prefixOverrides 會忽略以管道分隔的文本序列(此例中的空格是必要的),命中的內容被移除後再插入 prefix。
動態更新語句的等價方案是 set:
<update id="updateAuthorIfNecessary">
update Author
<set>
<if test="username != null">username=#{username},</if>
<if test="password != null">password=#{password},</if>
<if test="email != null">email=#{email},</if>
<if test="bio != null">bio=#{bio}</if>
</set>
where id=#{id}
</update>
set 會自動前置 SET 關鍵字並去掉多餘的尾逗號,等價 trim 寫法:
<trim prefix="SET" suffixOverrides=","> ... </trim>
遍歷集合構建 IN 條件是最常見的需求:
<select id="selectPostIn" resultType="domain.blog.Post">
SELECT *
FROM POST P
WHERE ID in
<foreach item="item" index="index" collection="list"
open="(" separator="," close=")">
#{item}
</foreach>
</select>
foreach 允許指定集合、元素變量與索引變量,還能設定開閉字符串與分隔符,並且很智能,不會多加分隔符。
傳入可迭代對象(List、Set 等)或數組時,index 是當前迭代次數,item 是本次元素;傳入字典(Map.Entry 集合)時,index 是鍵,item 是值。
<select id="selectBlogsLike" resultType="Blog">
<bind name="pattern" value="'%' + _parameter.getTitle() + '%'" />
SELECT * FROM BLOG
WHERE title LIKE #{pattern}
</select>
bind 從 OGNL 表達式創建變量並綁定到上下文,避免重複拼接。
配置了 databaseIdProvider 後,可在動態代碼中使用 _databaseId 變量:
<insert id="insert">
<selectKey keyProperty="id" resultType="int" order="BEFORE">
<if test="_databaseId == 'Oracle'">
select seq_users.nextval from dual
</if>
<if test="_databaseId == 'db2'">
select nextval for seq_users from sysibm.sysdummy1
</if>
</selectKey>
insert into users values (#{id}, #{name})
</insert>
MyBatis 從 3.2 起支持可插拔腳本語言,實現 LanguageDriver 接口即可:
public interface LanguageDriver {
ParameterHandler createParameterHandler(MappedStatement mappedStatement, Object parameterObject, BoundSql boundSql);
SqlSource createSqlSource(Configuration configuration, XNode script, Class<?> parameterType);
SqlSource createSqlSource(Configuration configuration, String script, Class<?> parameterType);
}
全局設置默認語言:
<typeAliases> <typeAlias type="org.sample.MyLanguageDriver" alias="myLanguage"/> </typeAliases> <settings> <setting name="defaultScriptingLanguage" value="myLanguage"/> </settings>
也可針對單條語句指定:
<select id="selectBlog" lang="myLanguage"> SELECT * FROM BLOG </select>
或使用註解:
public interface Mapper {
@Lang(MyLanguageDriver.class)
@Select("SELECT * FROM BLOG")
List<Blog> selectBlog();
}
Apache Velocity 也可以作為動態語言使用,細節可參考 MyBatis-Velocity 項目。
延伸閱讀:
MyBatis 入門學習教程 https://www.linuxidc.com/Linux/2015-02/113771.htm
Mybatis 實現單表的增刪改 https://www.linuxidc.com/Linux/2014-06/103456.htm
[Java][Mybatis] 物理分頁實現 https://www.linuxidc.com/Linux/2014-04/99889.htm
Mybatis 快速入門教程 https://www.linuxidc.com/Linux/2013-06/85762.htm
Mybatis 批量數據操作測試 https://www.linuxidc.com/Linux/2012-05/60863.htm
Mybatis 中 List 對象的批處理插入 https://www.linuxidc.com/Linux/2014-02/96916.htm