在实际项目开发过程中,存在大量的关联删除操作。
例如个人简历下面可能包括用户信息,用户工作经历,用户学历,用户技能等多个子表,当需要删除当前用户的所有信息时,不可能手动去关联删除或者在代码中多次执行不同表的删除操作。
此时你可能需要批量删除多表数据的写法,支持自定义参数。
需要特别注意的是,需要在数据库连接加上允许批量更新的属性
&allowMultiQueries=true
例如存在如下接口:
int dynamicBatchRemoveAllWeekData(Map<String,Object> params);
通过使用万能map构造自定义参数,支持一次性动态删除多个关联数据表的关联数据
Map<String,Object> params = new HashMap<>();
params.put("tableList",new String[]{
"week_disaster_response_child",
"week_important_work_child",
"week_common_child"
});
//测试数据仅供参考
params.put("ids",new Long[]{1L,2L});
params.put("tempTypeArray",new String[]{"01","02"});
对应的xml文件
注意该xml使用了statementType属性,该属性直接操作sql,不进行预编译,获取数据用$符号
<delete id="dynamicBatchRemoveAllWeekData" statementType="STATEMENT">
<foreach collection="tableList" item="tabName" index="index" >
delete from ${tabName} where bi_id in
<foreach item="id" collection="ids" open="(" separator="," close=")">
${id}
</foreach>
<if test="tabName == 'week_common_child' ">
and temp_type in
<foreach item="tempType" collection="tempTypeArray" open="(" separator="," close=")">
${tempType}
</foreach>
</if>
;
</foreach>
</delete>