Mybatis批量插入,批量更新

批量插入

  • xml如下:
<insert id ="batchInsert" parameterType="java.util.List" useGeneratedKeys="true" keyProperty="id">
        insert into t_person(name, age, height, weight, update_date) values
        <foreach collection="list" item="item" index="index" separator="," >
            (
            #{item.name},
            #{item.age},
            #{item.height},
            #{item.weight},
            now()
            )
        </foreach>
    </insert >

useGeneratedKeys="true"表示自动产生主键id,而keyProperty="id"表示主键对应的对象属性为id。

而且主键对应的这个Person对象的属性"id" (也可以是别的命名,比如personId之类的), 最好设置成String类型的,不然可能会出错。

  • Mapper如下:
void batchInsert(List<Person> personList);

这里不使用 @Param注解,那么在xml文件中的collection就默认为 "list"。

  • Service如下:
public void batchInsert(List<Person> personList) {
        if (CollectionUtils.isNotEmpty(personList)) {
          personMapper.batchInsert(personList);
        }
    }

在批量插入前,需要先做判空处理。

批量更新

  • xml如下:
<update id="batchUpdate" parameterType="java.util.List" >
	<foreach collection="list" item="item" index="index" open="" close="" separator=";">
		update t_person
		<set >
			<if test="item.name != null" >
				fbq_code = #{item.name,jdbcType=VARCHAR},
			</if>
			<if test="item.age != null" >
				dept_code = #{item.age,jdbcType=VARCHAR},
			</if>
			<if test="item.height != null" >
				emp_id = #{item.height,jdbcType=VARCHAR},
			</if>
			<if test="item.weight != null" >
				update_user = #{item.weight,jdbcType=VARCHAR },
			</if>
			update_date = now()
		</set>
		where id = #{item.id,jdbcType=INTEGER}
	</foreach>
</update>
  • Mapper如下:
void batchUpdate(List<Person> personList);
  • Service如下:
public void batchUpdate(List<Person> personList) {
        if (CollectionUtils.isNotEmpty(personList)) {
          personMapper.batchInsert(personList);
        }
    }

批量插入或者批量更新

如果需要先判断,不存在就插入,存在就更新。
可以使用INSERT ON DUPLICATE KEY UPDATE.
详情见: https://www.cnblogs.com/expiator/p/14417406.html

posted on   乐之者v  阅读(7177)  评论(0编辑  收藏  举报

编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示