MyBatis 的強大特性之一便是它的動態 SQL。如果你有使用 JDBC 或其它類似框架的經驗,你就能體會到根據不同條件拼接 SQL 語句的痛苦。例如拼接時要確保不能忘記添加必要的空格,還要注意去掉列表最后一個列名的逗號。利用動態 SQL 這一特性可以徹底擺脫這種痛苦。
雖然在以前使用動態 SQL 并非一件易事,但正是 MyBatis 提供了可以被用在任意 SQL 映射語句中的強大的動態 SQL 語言得以改進這種情形。
動態 SQL 元素和 JSTL 或基于類似 XML 的文本處理器相似。在 MyBatis 之前的版本中,有很多元素需要花時間了解。MyBatis 3 大大精簡了元素種類,現在只需學習原來一半的元素便可。MyBatis 采用功能強大的基于 OGNL 的表達式來淘汰其它大部分元素。
if
mapper中編寫sql,使用<if test = ' '> </if>
,可以使你的接口很便捷
舉個栗子:
select * from student
<if test = " id != null ">where student.id =#{id}
</if>
一個<if>
標簽還是不夠用的,你單獨使用<if>
的時候肯定還會遇到這樣的問題
select * from student
where
<if test = " id != null ">
student.id = #{id}
</if>
<if test = " name != null and name != '' ">
and student.name = #{name}
</if>
如果當你的id為空時,name
前面的and
是沒有必要的,運行會拋異常
或者當這兩個<if>
都為空時,只剩一個空的where,還是會報錯
where
select * from student
<where>
<if test = " id != null ">and student.id = #{id}
</if>
<if test = " name != null and name != '' ">and student.name = #{name}
</if>
</where>
where
元素只會在至少有一個子元素的條件返回 SQL 子句的情況下才去插入WHERE
子句。而且,若語句的開頭為AND
或OR
,where
元素也會將它們去除。
if-else =>> choose, when, otherwise
首先,在myBatis中是不支持if-else的,想要是用if-else的話,可以使用choose
代替。choose,when,otherwise
有點像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>
關于mybatis的動態sql,建議查看,中文哦官方文檔