mybatis 批量更新/插入
阿新 • • 發佈:2019-01-11
一. 批量更新
介面
void batchUpdate(List<OrderItem> oiList);
XML檔案
<update id="batchUpdate" parameterType="java.util.List"> <foreach collection="list" item="oiList" index="index" open="" close="" separator=";"> update order_item <set> child_order_no = #{oiList.childOrderNo} </set> where id_ = #{oiList.id} </foreach> </update>
最終執行的SQL語句如下:
Preparing: update order_item SET child_order_no = ? where id_ = ? ; update order_item SET child_order_no = ? where id_ = ? ; update order_item SET child_order_no = ? where id_ = ?
以分號分隔兩個更新的SQL語句
二. 批量插入
介面
void batchInsert(@Param("japList") List<ActivityPublish> japList, @Param("actId") String actId);
XML檔案
<insert id="batchInsert" parameterType="java.util.List"> delete from activity_publish where act_id = #{actId}; insert into activity_publish (id_, tenant_id, act_id, create_by, create_time, update_by, update_time) values <foreach collection="japList" item="item" index="index" separator=","> ( #{item.id}, #{item.tenantId},#{item.actId}, #{item.createBy}, #{item.createTime},#{item.updateBy}, #{item.updateTime} ) </foreach> </insert>
這裡我執行了兩個操作,先是根據actId刪除相應的資料,再進行批量的插入,兩個SQL語句可以一起執行。
foreach 這句有點像java的 foreach,例如:
for (ActivityPublish item : japList) {
System.out.println(item.id);
}