原始版删除单个或多个数据
dao层接口写法
/**
* 基于记录id执行删除业务(有些公司,记录不会
* 直接删除,而是在删除时修改其状态)
* @param ids
* @return rows
*/
int deleteObjects(@Param("ids")Integer...ids);
接下来是几种sql对比
下面写法是原始状态,如果传入0或null需要注意
<delete id="deleteObjects">
delete from sys_logs
where id in
<foreach collection="ids"
open="("
close=")"
separator=","
item="id">
#{id}
</foreach>
</delete>
下面写法避免了null和0的情况
<delete id="deleteObjects">
delete from sys_logs
<if test="ids ==null || ids.length == 0">
where id=-1
</if>
<if test="ids !=null and ids.length>0">
where ids in
<foreach collection="ids"
open="("
close=")"
separator=","
item="id">
#{id}
</foreach>
</if>
</delete>
首先分析一下,in或not in一般避免使用,效率慢,那么改版如下
这样避免使用in但是传入null和0,负数还是不行
<delete id="deleteObjects">
delete from sys_logs
<!-- 相当于 where id=1 or id=2 or id=3 -->
<where>
<foreach collection="ids"
separator="or"
item="id">
id=#{id}
</foreach>
</where>
</delete>
那么可以这样优化
要么执行when,要么then之后的-1
<delete id="deleteObjects">
delete from sys_logs
<where>
<choose>
<when test="ids!=null and ids.length>0">
<foreach collection="ids"
separator="or"
item="id">
id=#{id}
</foreach>
</when>
<otherwise>
id=-1
</otherwise>
</choose>
</where>
</delete>