SQL(1) 批量处理

mybatis中批量处理更新

1.在jdbc连接URL加上&allowMultiQueries=true, 支持批量操作

jdbc:mysql://192.168.99.100:3306/migu_cms?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT&allowMultiQueries=true

2. 批量更新
(1)使用foreach这样,一条记录update一次,性能比较差,容易造成阻塞
<update id="updateSortBatch" parameterType="java.util.List">
    <foreach collection="list" item="banner">
      update t_banner_record set sort_id = #{banner.sortId} where id=#{banner.id}
    foreach>
update>

(2)使用case when实现

实际的sql格式

UPDATE course
    SET name = CASE id 
        WHEN 1 THEN 'name1'
        WHEN 2 THEN 'name2'
        WHEN 3 THEN 'name3'
    END, 
    title = CASE id 
        WHEN 1 THEN 'New Title 1'
        WHEN 2 THEN 'New Title 2'
        WHEN 3 THEN 'New Title 3'
    END
WHERE id IN (1,2,3)
<update id="updateSortBatch" parameterType="java.util.List">
    update t_banner_record
    <trim prefix="set" suffixOverrides=",">
      <trim prefix="sort_id=case" suffix="end,">
        <foreach collection="list" item="banner" index="index">
          when id=#{banner.id} then #{banner.sortId}
        foreach>
      trim>
    trim>
    where id in
    <foreach collection="list" item="banner" index="index" separator="," open="(" close=")">
      #{banner.id}
    foreach>
  update>

 

你可能感兴趣的:(SQL(1) 批量处理)