本文测试三种方式,插入大量数据(10万以上)到mysql数据库中,有以下几种方式
- 普通方式
- foreach批量插入
- ExecutorType.BATCH插入
1 user实体类
@Setter
@Getter
public class User {
private Long id;
private String phone;
private String name;
}
2 IUserService
public interface IUserService {
void insertUsers();
void insertUser();
void batchInsert();
void insertUsersBatch();
}
3 userService类
package com.bear.dbinserttest;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
/**
* @description:
* @author: zhoushaoxiong
* @date: 2023/6/8 11:08
*/
@Service
public class UserService implements IUserService {
private static int count = 1000000;
@Resource
private IUserDao userDao;
@Autowired
private SqlSessionTemplate sqlSessionTemplate;
@Override
public void insertUser(){
List<User> userList = new ArrayList<>();
Long start = System.currentTimeMillis();
for (int i=0; i<count; i++){
User user = new User();
user.setName("name"+i);
user.setPhone("phonephone"+i);
userList.add(user);
userDao.insertUser(user);
}
Long usedTime = (System.currentTimeMillis()-start);
System.out.println("插入"+count+"条数据耗时::" + usedTime);
}
@Override
//foreach插入
public void insertUsers()