Mybatis 遍历(二)

最近碰到了关于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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值