1: 最简单的就是在service 中使用 for循环的批量插入
for (int i = 1; i <= num; i++) {
User user = new User();
user.setUserName("a" + i);
user.setCreateDate(new Date());
userDao.insertUser(user);
}
2: 使用mybatis 的 foreach 动态标签的批量插入
@Test public void testInsertBatch() throws Exception { long start = System.currentTimeMillis(); List<User> list = new ArrayList<>(); User user; for (int i = 0; i < 10000; i++) { user = new User(); user.setId("test" + i); user.setName("name" + i); user.setDelFlag("0"); list.add(user); } userService.insertBatch(list); long end = System.currentTimeMillis(); System.out.println("---------------" + (start - end) + "---------------"); }
<insert id="insertBatch"> INSERT INTO t_user (id, name, del_flag) VALUES <foreach collection ="list" item="user" separator =","> (#{user.id}, #{user.name}, #{user.delFlag}) </foreach > </insert>