mybatis 批量插入 DUPLICATE KEY UPDATE
可以直接粘贴代码:
insert into tableName(表字段1,表字段2) values <foreach collection="list" item="item" index="index" separator=","> (#{item.参数1},#{item.参数2}) </foreach> (如果主键则更新) ON DUPLICATE KEY UPDATE 表字段1 = 表字段1,表字段2 = 表字段2;都是数据库字段 example: create table user( id int primary key, name varchar(20), pwd varchar(20) ); 使用上面的新增存在则更新 insert into tableName(name,pwd) values <foreach collection="list" item="item" index="index" separator=","> (#{item.name},#{item.pwd}) </foreach> ON DUPLICATE KEY UPDATE name= name,pwd = pwd;
上述代码块SQL如下:
insert into tableName(表字段1,表字段2) values (?,?),(?,?),(?,?),(?,?)
update tableName set ...
你可以将任何可迭代对象(如 List、Set 等)、Map 对象或者数组对象作为集合参数传递给 foreach。当使用可迭代对象或者数组时,index 是当前迭代的序号,item 的值是本次迭代获取到的元素。当使用 Map 对象(或者 Map.Entry 对象的集合)时,index 是键,item 是值。
foreach 支持:list 、set 、map、array数组
map的时候,index是建,item是值。