需求:动物查询,如果传过来的id集合非空,遍历集合查询,否则做全表查询:
<select id="listAnimals" resultType="com.zhang.entity.Animal">
SELECT * FROM animal
WHERE 1=1
<if test="ids != null and ids.size() > 0">
and `id` in
<foreach collection="ids" item="id" index="index"
open="(" close=")" separator=",">
#{id}
</foreach>
</if>
</select>
也可以把条件嵌入左边圆括号 "(" 中:
<select id="listAnimals" resultType="com.zhang.entity.Animal">
SELECT * FROM animal
WHERE 1=1
<if test="ids != null and ids.size() > 0">
<foreach collection="ids" item="id" index="index"
open="and `id` in (" close=")" separator=",">
#{id}
</foreach>
</if>
</select>
肉眼看上去,好像第二种方式更快一些~