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);