MyBatis 的一個(gè)強(qiáng)大的特性之一通常是它的動(dòng)態(tài) SQL 能力。如果你有使用 JDBC 或其他 相似框架的經(jīng)驗(yàn),你就明白條件地串聯(lián) SQL 字符串在一起是多么的痛苦,確保不能忘了空格或在列表的最后省略逗號(hào)。動(dòng)態(tài) SQL 可以徹底處理這種痛苦。
動(dòng)態(tài)SQL
MyBatis的動(dòng)態(tài)SQL,解決了SQL字符串拼接的痛苦。
1.if
1
2
3
4
5
6
7
8
|
< select id= "findActiveBlogWithTitleLike" parameterType= "Blog" resultType= "Blog" > SELECT * FROM BLOG WHERE state = 'ACTIVE' <if test= "title != null" > AND title like #{title} </if> </ select > |
這條一句會(huì)提供一個(gè)可選的文本查找功能。如果沒(méi)有傳遞title,那么所有激活的博客都會(huì)被返回。
如果傳遞了title,那么就會(huì)查找相近的title。
2.choose,when,otherwise
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
< select id= "findActiveBlogLike" parameterType= "BLOG" resultType= "BLOG" > SELECT * FROM BLOG WHERE <choose> < when test= "title != null" > AND title like #{title} </ when > < when test= "author != null and author.name != null" > AND title like #{author. name } </ when > <otherwise> AND featured = 1 </otherwise> </choose> </ select > |
注:如果上述條件都沒(méi)有匹配,則會(huì)變成SELECT * FROM BLOG WHERE
如果僅有第二個(gè)匹配,則會(huì)變成SELECT * FROM BLOG WHERE AND title LIKE somelike
顯然這樣會(huì)查詢失敗。要解決這個(gè)問(wèn)題,mybatis提供了解決方法。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
< select id= "findActiveBlogLike" parameterType= "BLOG" resultType= "BLOG" > SELECT * FROM BLOG WHERE <trim prefix= "WHERE" prefixOverrides= "AND |OR " > <choose> < when test= "title != null" > AND title like #{title} </ when > < when test= "author != null and author.name != null" > AND title like #{author. name } </ when > <otherwise> AND featured = 1 </otherwise> </choose> </trim> </ select > |
overrides屬性采用管道文本分隔符來(lái)覆蓋,這里的空白是重要的。它的結(jié)果就是移除在InnerText中overrides中指定的內(nèi)容。
3.set
1
2
3
4
5
6
7
8
9
10
|
< update id= "updateAuthorIfNecessary" parameterType= "Author" > update Author < set > <if test= "username != null" >username=#{username},</if> <if test= "password != null" > password =#{ password },</if> <if test= "email != null" >email=#{email}</if> </ set > where id=#{id} </ update > |
同上的問(wèn)題,優(yōu)化后:
1
2
3
4
5
6
7
8
9
10
11
12
|
< update id= "updateAuthorIfNecessary" parameterType= "Author" > update Author <trim prefix= "where" prefixOverrides= "," > < set > <if test= "username != null" >username=#{username},</if> <if test= "password != null" > password =#{ password },</if> <if test= "email != null" >email=#{email}</if> </ set > where id=#{id} </trim> </ update > |
以上所述是小編給大家介紹的MyBatis 動(dòng)態(tài)拼接Sql字符串的問(wèn)題,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)服務(wù)器之家網(wǎng)站的支持!