MyBatis 的一個強大的特性之一通常是它的動態SQL 能力。如果你有使用JDBC 或其他相似框架的經驗,你就明白條件地串聯SQL 字符串在一起是多麼的痛苦,確保不能忘了空格或在列表的最後省略逗號。動態SQL 可以徹底處理這種痛苦。
動態SQL
MyBatis的動態SQL,解決了SQL字符串拼接的痛苦。
1.if
<select id="findActiveBlogWithTitleLike"parameterType="Blog" resultType="Blog">SELECT * FROM BLOGWHERE state = 'ACTIVE'<if test="title != null">AND title like #{title}</if></select>這條一句會提供一個可選的文本查找功能。如果沒有傳遞title,那麼所有激活的博客都會被返回。
如果傳遞了title,那麼就會查找相近的title。
2.choose,when,otherwise
<select id="findActiveBlogLike"parameterType="BLOG" resultType="BLOG">SELECT * FROM BLOGWHERE<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>注:如果上述條件都沒有匹配,則會變成SELECT * FROM BLOG WHERE
如果僅有第二個匹配,則會變成SELECT * FROM BLOG WHERE AND title LIKE somelike
顯然這樣會查詢失敗。要解決這個問題,mybatis提供了解決方法。
<select id="findActiveBlogLike"parameterType="BLOG" resultType="BLOG">SELECT * FROM BLOGWHERE<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屬性採用管道文本分隔符來覆蓋,這裡的空白是重要的。它的結果就是移除在InnerText中overrides中指定的內容。
3.set
<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>同上的問題,優化後:
<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 動態拼接Sql字符串的問題,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對武林網網站的支持!