您的位置:首页 > 博客中心 > 互联网 >

Mybatis批量插入,批量更新

时间:2022-05-11 08:44

批量插入

  • xml如下:

        insert into t_person(name, age, height, weight, update_date) values
        
            (
            #{item.name},
            #{item.age},
            #{item.height},
            #{item.weight},
            now()
            )
        
    

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

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

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

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

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

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

批量更新

  • xml如下:

	
		update t_person
		
			
				fbq_code = #{item.name,jdbcType=VARCHAR},
			
			
				dept_code = #{item.age,jdbcType=VARCHAR},
			
			
				emp_id = #{item.height,jdbcType=VARCHAR},
			
			
				update_user = #{item.weight,jdbcType=VARCHAR },
			
			update_date = now()
		
		where id = #{item.id,jdbcType=INTEGER}
	

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

本类排行

今日推荐

热门手游