Mybatis批量操作sql寫法
批量Insert,參數爲List<Object>
mysql的批量新增sql的寫法示例,先看一下mapper的寫法;
void batchSaveUser(List<SysUser> userList);
接下來看sql如何寫;
<insert id="batchSaveUser">
insert into sys_user (ding_user_id, username, nickname, password, email,
mobile, avatar, creator_id, create_time, updator_id, update_time, is_delete)
values
<foreach collection="list" item="user" separator=",">
(
#{user.dingUserId}, #{user.username}, #{user.nickname}, #{user.password}, #{user.email},
#{user.mobile}, #{user.avatar}, #{user.creatorId}, now(), #{user.updatorId}, now(), 0
)
</foreach>
</insert>
批量Insert,參數爲Map<Long, List<Long>>
void batchSaveGroupAndUser(@Param("map") Map<Long, List<Long>> groupUserMap);
<insert id="batchSaveGroupAndUser" parameterType="java.util.Map">
insert into sys_group_member (group_id, user_id, creator_id, create_time)
values
<foreach collection="map.keys" item="groupId" separator=",">
<foreach collection="map[groupId]" item="userId" separator=",">
(
#{groupId}, #{userId}, 'admin', now()
)
</foreach>
</foreach>
</insert>
批量Update,參數爲List<Object>
**注意:**在執行批量Update的時候,數據庫的url配置需要添加一項參數:&allowMultiQueries=true
如果沒有這個配置參數的話,執行下面的更新語句會報錯:
<update id="batchUpdateCorporation" parameterType="java.util.List">
<foreach collection="list" item="item" index="index" separator=";">
update sys_corporation set
<if test="item.name != null and item.name !=''">
`name` = #{item.name},
</if>
<if test="item.code != null and item.code !=''">
code = #{item.code},
</if>
<if test="item.parentCode != null and item.parentCode !=''">
parent_code = #{item.parentCode},
</if>
updater = 'system',
update_time = now()
where id = #{item.id}
</foreach>
</update>