1. 程式人生 > 其它 >mubatis 使用批量的方式進行 insert插入和update 修改

mubatis 使用批量的方式進行 insert插入和update 修改

在Java程式碼種頻繁呼叫sql進行處理資料是比較費時間的。

那麼對於插入這種我們可用mybatis的批量插入進行insert資料 而不是迴圈一次調一次insert

寫法:

mapper:

Integer  createPlanByListEntity(List<Entity> list);
xml:parameterType就是傳入的list<實體>
<insert id="自己定義的id名" parameterType="java.util.List" >
    insert into 表名 (
        id, STATUS,CREATE_USER_NAME,CREATE_USER_ID,CREATE_TIME
    ) values 
    
<foreach item="item" collection="list" index="index" separator=","> (#{item.id},#{item.status},#{item.whsCompanyId},#{item.whsCode},#{item.whsName},#{item.appointmentType},#{item.startTime},#{item.endTime}, #{item.intervalTimeUnit},#{item.intervalTime},#{item.appointmentDay},#{item.appointmentStockType},#{item.appointmentUnit}, #{item.appointmentWeight},#{item.createUserName},#{item.createUserId},#{item.createTime} )
</foreach> </insert>

批量修改寫成

update 表名 set status =1 where id =1;

update 表名 set status =2 where id =2;

這種格式就是分號隔開的多個update

程式碼 只貼xml 了

<update id="自己起個"  parameterType="java.util.List">
    <foreach collection="list" item="item"  separator=";">
        update 表名
        <set>
             
            <if
test="item.updateUserName != null and item.updateUserName != ''"> UPDATE_USER_NAME = #{item.updateUserName}, </if> <if test="item.updateUserId != null and item.updateUserId != ''"> UPDATE_USER_ID = #{item.updateUserId}, </if> <if test="item.updateTime != null "> UPDATE_TIME = #{item.updateTime} </if> </set> where id = #{item.id} </foreach> </update>

注意批量update需要設定資料庫的連線加上這個:&allowMultiQueries=true 否則會報錯