这种情况属于增删改查条件为集合时遇到。例如想要删除10个用户,根据id删除,如果每次只传入一个id,那么需要执行10条delete语句,如果利用foreach后一条语句就搞定,下面列举出一个简单的方法,
比如:
mapper里面的类方法:
(1)public void delRelative(PatientRelativeDto ratientRelativeDto) throws Exception;
与其对应的xml语句:
(2)
<delete id="delRelative" parameterType="PatientRelativeDto">
delete from t_patient_relative
where patientId = #{patientId} and id in
<foreach collection="idList" item="id" index="index" open="(" close=")" separator=",">
#{id}
</foreach>
</delete>
解释:(1)中的参数ratientRelativeDto是一个实体类,里面有属性patientId 和idList集合,这两个参数在(2)中作为参数;注意:collection等于的值必须是实体类中含有的属性,这里是集合idList,否则sql会报错,
其中
foreach元素的属性主要有 item,index,collection,open,separator,close。
item表示集合中每一个元素进行迭代时的别名.
index指 定一个名字,用于表示在迭代过程中,每次迭代到的位置.
open表示该语句以什么开始,separator表示在每次进行迭代之间以什么符号作为分隔 符.
close表示以什么结束.