天天看點

myBatis xml if、where、if-else?、foreach 心得ifwhereif-else =>> choose, when, otherwise

文章轉載自:https://blog.csdn.net/qq_34886018/article/details/86478403

       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,建議檢視,中文哦官方文檔