MyBatis之動態SQL基本用法
阿新 • • 發佈:2022-04-09
MyBatis之動態SQL基本用法
if
if只能簡單的進行條件的判斷
在簡單的一個條件中可以使用
<select id="findActiveBlogWithTitleLike" resultType="Blog">
SELECT * FROM BLOG
WHERE state = ‘ACTIVE’
<if test="title != null">
AND title like #{title}
</if>
</select>
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>
where
where 標籤會自動處理只有在一個以上的< if >標籤有值時才去插入“WHERE”子句到SQL中。
where標籤會自動去除首個條件中的AND,可以不用去管第一個條件是否為空可以直接給所有if標籤中的條件都加上AND,但一般習慣第一個條件去掉AND ,但是如果遇到前邊已經有一個存在的條件的情況下,那接下來所有的if中的條件開頭AND是必須要加的.而且,若子句的開頭為 “AND” 或 “OR”,where 元素也會將它們去除。*
總的來說就是在多個條件判斷的時候用where,第一個子句習慣不加and,後面的子句都要加and
<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>
set
set 元素會動態地在行首插入 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>
foreach
動態 SQL 的另外一個常用的必要操作是需要對一個集合進行遍歷,通常是在構建 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 例項或者陣列作為引數物件傳給 MyBatis,當你這麼做的時候,MyBatis 會自動將它包裝在一個 Map 中並以名稱為鍵。List 例項將會以"list"作為鍵,而陣列例項的鍵將是"array"。
如果有什麼錯誤,歡迎各位大佬指出,同時也希望大家可以評論自己見解,一起學習一起進步!