项目中,为了提高效率和方便回滚,不单单只是在mvc的服务层设置回滚切点,最好是能在sql里面实现批量更新最好不过了。
mybatis作为强大的持久层框架,当然可以很好地支持批量更新。而且以下代码兼容oracle和mysql数据库
一、不同的id更新相同值的几个字段。
传值是map类型,ids可以是list也可以是数组。
<update id="updatebatchSame" parameterType="java.util.Map" >
UPDATE Table1 SET name = #{name},code=#{code} WHERE id IN
<foreach collection="ids" index="index" item="item" open="(" separator="," close=")">
#{item}
</foreach>
</update>
二、多个不同的条件(id和bid)更新相同值的几个字段。
传值是map类型,ids是List,不同的条件在list元素对象里。
<update id="updatebatchMore" parameterType="java.util.Map" >
UPDATE Table1 SET name = #{name},code=#{code} WHERE
<foreach collection="ids" index="index" item="item" separator="or" >
(id=#{item.id} and bid=#{item.bid})
</foreach>
</update>
三、 不同的id更新不同值的几个字段。
传值是map类型,ids是List,所有的值都在List元素对象里面。
<update id="updatebatchIdList" parameterType="java.util.Map" >
UPDATE Table1 SET name =
<foreach collection="ids" index="index" item="item" open="case id" separator=" " close=" end">
when #{item.id} then #{item.name}
</foreach>
,code= <foreach collection="ids" index="index" item="item" open="case id" separator=" " close=" end">
when #{item.id} then #{item.code}
</foreach>
WHERE id IN
<foreach collection="ids" index="index" item="item" open="(" separator="," close=")">
#{item.id}
</foreach>
</update>
四、 多个不同的条件(id和bid)更新不同值的几个字段。
传值是map类型,ids是List,所有的值都在List元素对象里面。
<update id="updatebatchList" parameterType="java.util.Map" >
UPDATE Table1 SET name =
<foreach collection="ids" index="index" item="item" open="case " separator=" " close=" end">
when (id=#{item.id} and bid=#{item.bid}) then #{item.name}
</foreach>
,code= <foreach collection="ids" index="index" item="item" open="case " separator=" " close=" end">
when (id=#{item.id} and bid=#{item.bid}) then #{item.code}
</foreach>
WHERE
<foreach collection="ids" index="index" item="item" separator="or" >
(id=#{item.id} and bid=#{item.bid})
</foreach>
</update>