當一條SQL中既有條件查又有模糊查的時候,偶爾會遇到這樣的and拼接問題。參考如下代碼:
<select id="listSelectAllBusiness"> select * from *** where <if test="a!= null"> a = #{a} </if> <if test="b!= null"> and b in <foreach collection="list" index="index" item="item" open="(" separator="," close=")"> #{item} </foreach> </if> <if test="c!= null"> and name like '%${c}%' or code like '%${c}%' </if> order by id desc limit #{limit} offset #{page} </select>
這樣寫的錯誤是如果a==null那么第二個條件中就會多一個and,語句會變成select * from *** where and b in (...),而如果條件全都不滿足的話SQL會變成select * from *** where order by id desc limit...解決辦法:加上<where>標簽,如下:
<select id="listSelectAllBusiness"> select * from *** <where> <if test="a!= null"> a = #{a} </if> <if test="b!= null"> and b in <foreach collection="list" index="index" item="item" open="(" separator="," close=")"> #{item} </foreach> </if> <if test="c!= null"> and name like '%${c}%' or code like '%${c}%' </if> </where> order by id desc limit #{limit} offset #{page} </select>
如上代碼所示,加上一個<where>標簽即可,where標簽會自動識別,如果前面條件不滿足的話,會自己去掉and。如果滿足的話會自己加上and。但是這句語句還是有問題,就是c條件里的語句里面有一個or,如果前面全部ab條件中有滿足的話就會形成這樣的SQL,select * from *** where a = ? and name like '%%' or code like '%%',這條就類似SQL注入了,只要后面or條件滿足都能查出來,不滿足需求。解決辦法:給c條件的語句加上(),如下:
<select id="listSelectAllBusiness"> select * from *** <where> <if test="a!= null"> a = #{a} </if> <if test="b!= null"> and b in <foreach collection="list" index="index" item="item" open="(" separator="," close=")"> #{item} </foreach> </if> <if test="c!= null"> and (name like '%${c}%' or code like '%${c}%') </if> </where> order by id desc limit #{limit} offset #{page} </select>