数据库批量操作(批量更新,批量插入)

数据库的批量操作

为了尽可能提高我们的sql执行效率,一般我们针对多条数据的操作,使用批量更新或者批量插入的方式 方式如下:

--批量插入
<insert id="saveUserList" parameterType="java.util.List">
        insert into test
        (id,name)
        values
        <foreach collection="list" item="user" separator=",">
            (
            #{user.id},
            #{user.name}
            
            )
        </foreach>
    </insert>

  
批量更新(使用方式一效率较高)
方式一:  

 <update id="batchUpdateUser" parameterType="java.util.Map" >
          update user t
        set
        pay_status=r.status,

        updated_date =now(),
        updated_by=#{paramMap.currentUser}
       from (
        <foreach collection="paramMap.list" item="i" separator="union all">
            select #{i.id}::text id,
            #{i.status}::text  status

        </foreach>

        ) r
        where r.id=t.id
    </update>
方式二:
<update id="batchUpdateUser">
        update user
        set name =
        <foreach collection="list" item="item" index="index"
            separator=" " open="case ID" close="end">
            when #{item.id} then
            #{item.name}
        </foreach>
       
        where id in
        <foreach collection="list" item="item" index="index"
            separator="," open="(" close=")">
            #{item.id,jdbcType=VARCHAR}
        </foreach>

    </update>
    ```
    


猜你喜欢

转载自blog.csdn.net/hbn1326317071/article/details/84108381