mybatis实现数据库批量插入两种方式
一、一次插入多个对象
<insert id="addList">
insert into user
(name,age,mobilephone,sex,birthday,email) values
<foreach collection="contactInfos" item="item" open="(" close=")" separator="),(">
#{item.name,jdbcType=VARCHAR},
#{item.age,jdbcType=INTEGER},
#{item.mobilephone,jdbcType=VARCHAR},
#{item.sex,jdbcType=INTEGER},
#{item.birthday,jdbcType=TIMESTAMP},
#{item.email,jdbcType=VARCHAR}
</foreach>
</insert>
二、一次插入一个map集合,value为List
String uid = "aaa";
List<String> phoneList;
List<String> emailList;
List<Map> mapList = new ArrayList<>();
for (int i=0; i<phoneList.size(); i++) {
Map map = new HashMap();
map.put("phone",phoneList.get(i));
map.put("email",emailList.get(i));
mapList.add(map);
}
contactMapper.addList(uid, mapList);
<insert id="addList">
insert into contact values
<foreach collection="contactMapList" item="map" index="index" close=";" separator=",">
(#{uid},
#{map.phone},
#{map.email})
</foreach>
</insert>