mybatis更新数据set加if_转载:mybatis批量更新数据三种⽅
实现⽅式有三种,
⼀种⽤for循环通过循环传过来的参数集合,循环出N条sql,
⽤mysql的case when 条件判断变相的进⾏批量更新
是⽤ON DUPLICATE KEY UPDATE进⾏批量更新
注意第⼀种⽅法要想成功,需要在db链接url后⾯带⼀个参数  &allowMultiQueries=true
jdbc:mysql://localhost:3306/mysqlTest?characterEncoding=utf-8&allowMultiQueries=true
第⼀种 for循环
批量更新sql语句update standard_relation
standard_from_uuid = #{item.standardFromUuid,jdbcType=VARCHAR},
standard_to_uuid = #{item.standardToUuid,jdbcType=VARCHAR},
gmt_modified = #{Modified,jdbcType=TIMESTAMP},
where id = #{item.id,jdbcType=BIGINT}
第⼆种 case when
update standard_relation
when id=#{i.id} then #{i.standardFromUuid}
when id=#{i.id} then #{i.standardToUuid}
when id=#{i.id} then #{i.gmtModified}
where
id=#{i.id}
第三种 ON DUPLICATE KEY UPDATE
insert into standard_relation(id,relation_type, standard_from_uuid,
standard_to_uuid, relation_score, stat,
last_process_id, is_deleted, gmt_created,
gmt_modified,relation_desc)VALUES
(#{item.id,jdbcType=BIGINT},
#{lationType,jdbcType=VARCHAR},
#{item.standardFromUuid,jdbcType=VARCHAR},
#{item.standardToUuid,jdbcType=VARCHAR},
#{lationScore,jdbcType=DECIMAL},
#{item.stat,jdbcType=TINYINT},
#{item.lastProcessId,jdbcType=BIGINT},
#{item.isDeleted,jdbcType=TINYINT},
#{Created,jdbcType=TIMESTAMP},
#{Modified,jdbcType=TIMESTAMP},
#{lationDesc,jdbcType=VARCHAR})
ON DUPLICATE KEY UPDATE
id=VALUES(id),relation_type = VALUES(relation_type),
standard_from_uuid = VALUES(standard_from_uuid),
standard_to_uuid = VALUES(standard_to_uuid),
relation_score = VALUES(relation_score),
stat = VALUES(stat),
last_process_id = VALUES(last_process_id),
is_deleted = VALUES(is_deleted),
gmt_created = VALUES(gmt_created),
gmt_modified = VALUES(gmt_modified),
relation_desc = VALUES(relation_desc)
测试运⾏效率
sql语句for循环效率其实相当⾼的,因为它仅仅有⼀个循环体,只不过最后update语句⽐较多,量⼤了就有可能造成sql阻塞。
case when虽然最后只会有⼀条更新语句,但是xml中的循环体有点多,每⼀个case when 都要循环⼀遍list集合,所以⼤批量拼sql的时候会⽐较慢,所以效率问题严重。使⽤的时候建议分批插⼊。
duplicate key update可以看出来是最快的,但是⼀般⼤公司都禁⽤,公司⼀般都禁⽌使⽤replace into和INSERT INTO … ON DUPLICATE KEY UPDATE,这种sql有可能会造成数据丢失和主从上表的⾃增id值不⼀致。⽽且⽤这个更新时,记得⼀定要加上id,⽽且values()括号⾥⾯放的是数据库字段,不是java对象的属性字段。
根据效率,安全⽅⾯综合考虑,选择适合的很重要。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。