Mybatis批量更新的两种方式

前言

在使用Mybatis框架的过程中,经常会通过构建动态SQL来处理批量插入,批量更新数据等相关操作,本文将以批量更新为例,简单介绍其使用过程

动态SQL元素

if set trim foreach

批量更新

映射方法

1
int updateOrderItem(List<OrderItem> list);

实体类字段

1
2
3
4
5
6
7
public class OrderItem {
private Integer id;
private Integer orderId;
private Integer productId;
private Integer count;
//省略...
}

测试代码

1
2
3
4
5
6
7
8
9
10
List<OrderItem> list=new ArrayList<>();
OrderItem orderItem=new OrderItem();
orderItem.setCount(66);
orderItem.setId(1);
OrderItem orderItem1=new OrderItem();
orderItem1.setCount(5);
orderItem1.setId(2);
list.add(orderItem);
list.add(orderItem1);
orderItemMapper.updateOrderItem(list);

方式一

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<update id="updateOrderItem"  parameterType="java.util.List">
<foreach collection="list" item="item" separator=";">
update order_item
<set>
<if test="item.orderId != null">
order_id = #{item.orderId},
</if>
<if test="item.productId != null">
product_id = #{item.productId},
</if>
<if test="item.count != null">
count = #{item.count}
</if>
</set>
where id = #{item.id}
</foreach>
</update>

对应SQL:

1
2
3
[cn.srblog.dao.OrderItemMapper.updateOrderItem]-==>  Preparing: update order_item SET count = ? where id = ? ; update order_item SET count = ? where id = ? 
[cn.srblog.dao.OrderItemMapper.updateOrderItem]-==> Parameters: 66(Integer), 1(Integer), 5(Integer), 2(Integer)
[cn.srblog.dao.OrderItemMapper.updateOrderItem]-<== Updates: 1

此方式需要允许MySQL的一次执行多条SQL

1
url=jdbc:mysql://localhost:3306/ssm?characterEncoding=utf-8&allowMultiQueries=true

方式二

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<update id="updateOrderItem"  parameterType="java.util.List">
update order_item
<trim prefix="set" suffixOverrides=",">
<trim prefix="orderId = case" suffix="end,">
<foreach collection="list" item="item">
<if test="item.orderId != null">
when id=#{item.id} then #{item.orderId}
</if>
</foreach>
</trim>
<trim prefix="productId = case" suffix="end,">
<foreach collection="list" item="item">
<if test="item.productId != null">
when id=#{item.id} then #{item.productId}
</if>
</foreach>
</trim>
<trim prefix="count = case" suffix="end,">
<foreach collection="list" item="item">
<if test="item.count != null">
when id=#{item.id} then #{item.count}
</if>
</foreach>
</trim>
</trim>
where id in
<foreach collection="idNames" index="index" item="item" open="(" separator="," close=")">
<if test="item.objectId != null">
#{item.id}
</if>
</foreach>
</update>

对应SQL

1
2
3
[cn.srblog.dao.OrderItemMapper.updateOrderItem]-==>  Preparing: update order_item set count = case when id=? then ? when id=? then ? end  where id in (?,?)
[cn.srblog.dao.OrderItemMapper.updateOrderItem]-==> Parameters: 1(Integer), 66(Integer), 2(Integer), 5(Integer),1(Integer), 2(Integer)
[cn.srblog.dao.OrderItemMapper.updateOrderItem]-<== Updates: 3

Mybatis批量更新的两种方式
https://www.srblog.cn/posts/bff75e50/
作者
sr
发布于
2019年4月23日
许可协议