MyBatis实现数据库批量插入
程序员文章站
2022-03-03 07:53:41
...
一、单个list,多个对象
1、应用场景:
一次插入多个对象
2、JAVA代码实现:
<insert id="addList">
insert into contact
(`name`,company,mobilephone,sex,birthday,`position`,email,telephone) values
<foreach collection="contactInfos" item="item" open="(" close=")" separator="),(">
#{item.name,jdbcType=VARCHAR},
#{item.company,jdbcType=VARCHAR},
#{item.mobilephone,jdbcType=VARCHAR},
#{item.sex,jdbcType=INTEGER},
#{item.birthday,jdbcType=TIMESTAMP},
#{item.position,jdbcType=VARCHAR},
#{item.email,jdbcType=VARCHAR},
#{item.telephone,jdbcType=VARCHAR}
</foreach>
</insert>
二、单个map,多个list
1、应用场景:
一次插入对象的多个属性分别的list
2、JAVA代码实现:
Service.java
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);
Mapper.xml
<insert id="addList">
insert into contact values
<foreach collection="contactMapList" item="map" index="index" close=";" separator=",">
(#{uid},
#{map.phone},
#{map.email})
</foreach>
</insert>
上一篇: 记录学习前端-------笔记01
下一篇: 记录学习----前端笔记02