文章目录
前言:这两天在做mybatis批量插入和更新的时候,对这块不是很清楚,所以今天写篇文章,巩固加深印象。
一、Mybatis批量插入
批量插入的sql 语句是:
insert into table (字段一,字段二,字段三) values(xx,xx,xx),(oo,oo,oo)
mybatis中mapper.xml的代码如下:
<!-- 批量插入数据 -->
<insert id="insertBatch" parameterType="java.util.List"
useGeneratedKeys="true">
insert into t_user
(name,age,address)
values
<foreach collection="list" item="user" index="index"
separator=",">
(
#{user.name},#{user.age},#{user.address}
)
</foreach>
</insert>
二、批量更新
批量更新数据使用的sql语句是:
UPDATE table
SET aa = CASE id
WHEN 1 THEN 'oo'
WHEN 2 THEN 'pp'
WHEN 3 THEN 'qq'
END
,SET bb = CASE id
WHEN 1 THEN 'xx'
WHEN 2 THEN 'yy'
WHEN 3 THEN 'zz'
END
WHERE id IN (1,2,3)
上面这一条mysql语句可以更新多条记录,mybatis中mapper.xml的代码如下:
<update id="updateBatch" parameterType="java.util.List">
update t_user
<trim prefix="set" suffixOverrides=",">
<trim prefix="name=case" suffix="end,">
<foreach collection="list" item="i" index="index">
<if test="i.name!=null">
when USER_ID=#{i.userId} then #{i.name}
</if>
</foreach>
</trim>
<trim prefix=" aget =case" suffix="end,">
<foreach collection="list" item="i" index="index">
<if test="i.aget!=null">
when USER_ID=#{i.userId} then #{i.aget}
</if>
</foreach>
</trim>
<trim prefix="address=case" suffix="end," >
<foreach collection="list" item="i" index="index">
<if test="i.address!=null">
when USER_ID=#{i.userId} then #{i.address}
</if>
</foreach>
</trim>
</trim>
where
<foreach collection="list" separator="or" item="i" index="index" >
USER_ID=#{i.userId}
</foreach>
</update>
名词解释:
foreach的主要用在构建in条件中,它可以在SQL语句中进行迭代一个集合。
foreach元素的属性主要有 item,index,collection,open,separator,close。
item表示集合中每一个元素进行迭代时的别名
index指定一个名字,用于表示在迭代过程中,每次迭代到的位置
open表示该语句以什么开始
separator表示在每次进行迭代之间以什么符号作为分隔 符
close表示以什么结束
在使用foreach的时候最关键的也是最容易出错的就是collection属性,该属性是必须指定的,但是在不同情况 下,该属性的值是不一样的,主要有一下3种情况:
1.如果传入的是单参数且参数类型是一个List的时候,collection属性值为list
2.如果传入的是单参数且参数类型是一个array数组的时候,collection的属性值为array
3.如果传入的参数是多个的时候,我们就需要把它们封装成一个Map了,当然单参数也可以封装成map
使用批量插入执行的SQL语句应该等价于: