最近碰到了关于mybatis遍历的需求:
总结一下:
当传入参数是Map<String, List> map这种类型时,
执行Select操作
假设传入某个参数为:Map<"userList", List<User> uesr> map
<select id="listData" resultType="userInfo">
select * from userinfo where id= #{id} and name in
<foreach collection="userList" item="item" index="index" open="(" separator="," close=")">
#{item}
</foreach>
</select>
map类型遍历: collection 填入需要遍历Map指定的key
其sql为:
select * from userinfo where id= ? and name in (?, ?)
执行update操作
如果是map类型,和上述一样
如果是List类型:
Mybatis批量update有两种
假设传入参数为: List<User> userList
1.执行多条SQL
<update parameteTyper="java.util.List">
<foreach collection="list" item="item" index="index" separator=";">
update userinfo set name= #{item.name} where id=#{item.id}
</foreach>
</update>
执行出来的sql大概是这样的:
update userinfo set name= ? where id=?;update userinfo set name= ? where id=?
但是执行这个多语句更新有几点需要注意:
1.执行效率低下,尤其在数据量比较大的情况
2.非要用这种方法的也可以,要在url上加上:&allowMultiQueries=true 主要针对Mysql数据库
2.使用单条sql批量更新
<update parameterType="java.util.List">
update userinfo
<trim prefix="set" suffixOverrides=",">
<trim prefix="name=case" suffix="end,">
<foreach collection="list" item="item" index="index">
<if test="item.name != null>
when id=#{item.id} then #{item.name}
</if>
</foreach>
</trim>
<!-- 如果有第二个set要写 -->
<trim prefix="address=case" suffix="end,">
<foreach collection="list" item="item" index="index">
when id=#{item.id} then #{item.address}
</foreach>
</trim>
</trim>
where id in
<foreach collection="list" item="item" index="index">
#{item.id}
</foreach>
</update>
转换成sql大概是:
UPDATE userinfo
SET name = CASE
WHEN id = ? THEN ?
WHEN id = ? THEN ?
END,
set address = case
WHEN id = ? THEN ?
WHEN id = ? THEN ?
END
WHERE id IN (?,?,?)
插入遍历:都差不多,写个例子体会下
<insert parameterType="java.util.List">
insert into userinfo (id, name, address)
<foreach collection="list" item="item" index="index" separator=",">
(#{item.id},#{item.name},#{item.address})
</foreach>
</insert>