Mybatis中and和or的细节处理
当一条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>