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字串的問題,希望對大家有所協助,如果大家有任何疑問請給我留言,小編會及時回複大家的。在此也非常感謝大家對雲棲社區網站的支援!