mybatis 的两种批量更新

470 阅读1分钟
  • 第一种 针对批量中的数据,每条数据更新的字段值和字段都不一样
update table1 set 
    field1=case 
    when id=xx1 then value1 
    `这里可以加if嵌套`
    when id=xx2 then value2 
    when id=xx3 then value3 
    end,
    field2=case 
    when id=xx1 then value1 
    when id=xx2 then value2 
    when id=xx3 then value3 
    end
    where id in(xx1,xx2,xx3) | where id=xx1 or id=xx2 or id=xx3
<update id="statBatch">
        update apd_user_task_data
        <trim prefix="set" suffixOverrides=",">
            batch_id=
            <foreach collection="records" item="item" open="case " close=" end,">
                when id = #{item.id,jdbcType=BIGINT} then #{batchId,jdbcType=BIGINT}
            </foreach>
            update_time=
            <foreach collection="records" item="item" open="case " close=" end,">
                when id = #{item.id,jdbcType=BIGINT} then #{item.updateTime,jdbcType=TIMESTAMP}
            </foreach>
            last_execute_time=
            <foreach collection="records" item="item" open="case " close=" end,">
                when id = #{item.id,jdbcType=BIGINT} then #{item.lastExecuteTime,jdbcType=TIMESTAMP}
            </foreach>
            status=
            <foreach collection="records" item="item" open="case " close=" end,">
                when id = #{item.id,jdbcType=BIGINT} then #{item.status,jdbcType=INTEGER}
            </foreach>
            volume=
            <foreach collection="records" item="item" open="case " close=" end,">
                when id = #{item.id,jdbcType=BIGINT} then #{item.volume,jdbcType=DECIMAL}
            </foreach>
            task_complete_time=
            <foreach collection="records" item="item" open="case " close=" end,">
                when  id = #{item.id,jdbcType=BIGINT} then #{item.taskCompleteTime,jdbcType=TIMESTAMP}
            </foreach>
        </trim>
        WHERE
        <foreach collection="records" item="item" open="( " separator=") or (" close=" )">
            id = #{item.id,jdbcType=BIGINT}
        </foreach>
    </update>
  • 第二种 将一组数据的某些字段更新为一个相同的值
update talbe1 set field1=xx1,field2=xx2 where id in(xx1,xx2)
<update id="batchUpdateBatchId" parameterType="java.util.List">
        update apd_user_task_data
        set batch_id=#{batchId}
        WHERE id in
        <foreach collection="dataList" item="item" open="(" separator="," close=")">
            #{item.id,jdbcType=BIGINT}
        </foreach>
    </update>