MyBatis 靜態拼接Sql字符串的成績。本站提示廣大學習愛好者:(MyBatis 靜態拼接Sql字符串的成績)文章只能為提供參考,不一定能成為您想要的結果。以下是MyBatis 靜態拼接Sql字符串的成績正文
MyBatis 的一個壯大的特征之一平日是它的靜態 SQL 才能。假如你有應用 JDBC 或其他 類似框架的經歷,你就明確前提地串連 SQL 字符串在一路是何等的苦楚,確保不克不及忘了空格或在列表的最初省略逗號。靜態 SQL 可以完全處置這類苦楚。
靜態SQL
MyBatis的靜態SQL,處理了SQL字符串拼接的苦楚。
1.if
<select id="findActiveBlogWithTitleLike"
parameterType="Blog" resultType="Blog">
SELECT * FROM BLOG
WHERE 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 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>
注:假如上述前提都沒有婚配,則會釀成SELECT * FROM BLOG WHERE
假如唯一第二個婚配,則會釀成SELECT * FROM BLOG WHERE AND title LIKE somelike
明顯如許會查詢掉敗。要處理這個成績,mybatis供給懂得決辦法。
<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屬性采取管道文天職隔符來籠罩,這裡的空白是主要的。它的成果就是移除在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字符串的成績,願望對年夜家有所贊助,假如年夜家有任何疑問請給我留言,小編會實時答復年夜家的。在此也異常感激年夜家對網站的支撐!