我们在操作一些数据的时候,可能会遇到同时改变被选中的多条数据的的某个值。接下来具体讲一下实现该操作的代码。
parameterType的值有两种情形。一种传过来的值是list,那么他的参数类型就是list,另一种传过来的值是array,那么他的参数类型是array。
foreach的主要参数有,item,index,collection,separator,open,close。
item:循环体中元素的别名,可随便去。该参数必填
index:在list和数组中,index是元素的序号,在map中,index是元素的key,该参数可选。
collection:如果传入的是List
<update id="updateBatch" parameterType="java.util.List">
<foreach collection="list" item="item" index="index" separator=";" open="" close="">
update REGION_CODE set
isactive =#{item.isactive},
classname=#{item.classname}
where id = #{item.id}
</foreach>
</update>
如上所写,运行报错,因为Mybatis映射文件中的sql语句不允许 ; 符号。所以我们按照case when的方式,把代码改改
<update id="batchUpdate" parameterType="java.util.List">
update r_user set
isactive =
<foreach collection="list" item="item" index="index"
separator=" " open="case id" close="end">
when #{item.id} then #{item.isactive}
</foreach>
,classname=
<foreach collection="list" item="item" index="index"
separator=" " open="case id" close="end">
when #{item.id} then #{item.classname}
</foreach>
where id in
<foreach collection="list" item="item" index="index"
separator="," open="(" close=")">
#{item.id}
</foreach>
</update>
批量更新的方法完毕,批量插入数据,批量删除数据的实现方式也大同小异。就不再赘述了