巧妙mybatis避免Where 空條件的尷尬


我就廢話不多說了,大家還是直接看代碼吧~

1
2
3
4
5
6
7
< select id = "findActiveBlogLike" resultType = "Blog" >
  SELECT * FROM BLOG
  WHERE
  < if test = "state != null" >
  state = #{state}
  </ if >
</ select >

如果state參數為空時,最終生成SQL語句為

SELECT * FROM BLOG

WHERE

執行會出錯,當然,你可以在where 后加一個1=1,改成

1
2
3
4
5
6
7
< select id = "findActiveBlogLike" resultType = "Blog" >
  SELECT * FROM BLOG
  WHERE 1=1
  < if test = "state != null" >
  and state = #{state}
  </ if >
</ select >

但是這個做法不太“環保”(畢竟引入了一個垃圾條件),其實只要改成<where>...</where>即可

1
2
3
4
5
6
7
8
< select id = "findActiveBlogLike" resultType = "Blog" >
  SELECT * FROM BLOG
  < where >
   < if test = "state != null" >
    and state = #{state}
   </ if >
  </ where >
</ select >


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM