MySql MyBatis 批量插入、更新
最近在公司项目中,遇到了个情景,需要跑批处理大批量的文件,并把数据库中原有的状态更新,之前有遇到过一条一条操作的情况,速度较慢,因此采用批量更新的方式操作数据。
看了不少博客,有人说需要加 allowMultiQueries=true 但我试过,只要mapper写的没问题,是可以不加的。
核心思路
采用mapper.batchUpdate(List<Object>)的方式替代for(Object obj : list ) {mapper.update(obj)}
实现的SQL
##插入sql
INSERT INTO person ( id, NAME, phone, address )
VALUES
( 1, 'name1', '11111111111', 'address1' ),
( 2, 'name2', '22222222222', 'address2' ),
(
3,
'name3',
'33333333333',
'address3'
);
##更新sql
UPDATE std_cert_no_image_detail
SET uploadStatus =
CASE
certNoImageFlowId
WHEN 3 THEN
'ends123'
WHEN 284 THEN
'12314'
END
WHERE
certNoImageFlowId IN (
3,
284);
Mapper.xml写法
<!--插入-->
<insert id="batchInsert">
insert into person(id,name,phone,address)
values
<foreach collection="list" item="item" index="index" separator=",">
(
#{item.id,jdbcType=INTEGER},
#{item.name,jdbcType=VARCHAR},
#{item.phone,jdbcType=VARCHAR},
#{item.address,jdbcType=VARCHAR}
)
</foreach>
</insert>
<!--更新-->
<update id="batchUpdateName" parameterType="list">
update person
<trim prefix="set" suffixOverrides=",">
<trim prefix="name = case id " suffix="end ">
<foreach collection="list" item="item" index="index">
<if test="item.name!= null">
when #{item.id} then #{item.name}
</if>
</foreach>
</trim>
</trim>
where id in
<foreach collection="list" item="item" index="index" open="( " separator="," close=" )">#{item.id}</foreach>
</update>
Java调用
//插入
mapper.batchInsert(personList);
//更新
mapper.batchUpdateName(personList);