Mybatis的and拼接问题
在具体业务开发中,有些业务涉及到多个可选的查询条件,例如要查询白天出现的时间段,晚上不出现时间段,这就涉及多个and拼接问题。
<select id="listSelectAll">
select * from ***
where
<if test="a!= null">
a = #{a}
</if>
<if test="b!= null">
and b = #{b}
</foreach>
</if>
<if test="c!= null">
and c = #{c}
</if>
order by id desc
limit #{limit} offset #{page}
</select>
这样写的错误是如果a==null那么第二个条件中就会多一个and,语句会变成select * from *** where and b =#{b},而如果条件全都不满足的话SQL会变成select * from *** where order by id desc limit…解决办法:加上<where>标签,如下:
<select id="listSelectAll">
select * from ***
<where>
<if test="a!= null">
a = #{a}
</if>
<if test="b!= null">
and b = #{b}
</foreach>
</if>
<if test="c!= null">
and c = #{c}
</if>
</where>
order by id desc
limit #{limit} offset #{page}
</select>
如上代码所示,加上一个<where>标签即可,where标签会自动识别,如果前面条件不满足的话,会自己去掉and。