mybatis 使用批量的方式進行 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  否則會報錯


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM