mybatis三種批量插入方式對比
阿新 • • 發佈:2018-12-18
準備:
1.表結構
CREATE TABLE `t_user` ( `id` varchar(32) CHARACTER SET utf8 NOT NULL COMMENT '主鍵', `name` varchar(50) CHARACTER SET utf8 DEFAULT NULL COMMENT '使用者名稱', `del_flag` char(1) CHARACTER SET utf8 DEFAULT NULL COMMENT '刪除標示', PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=latin1; |
2.1 jdbc.properties配置
mysql.driver=com.mysql.jdbc.Driver mysql.url=jdbc:mysql://127.0.0.1:3306/ssm mysql.username=root mysql.password=admin #定義初始連線數 mysql.initialSize=1 #定義最大連線數 mysql.maxActive=20 #定義最大空閒 mysql.maxIdle=20 #定義最小空閒 mysql.minIdle=1 #定義最長等待時間 mysql.maxWait=60000 |
<context:component-scan base-package |
第一種:普通for迴圈插入
①junit類
@Test public void testInsertBatch2() throws Exception { long start = System.currentTimeMillis(); User user; SqlSession sqlSession = sqlSessionTemplate.getSqlSessionFactory().openSession(false); UserDao mapper = sqlSession.getMapper(UserDao.class); for (int i = 0; i < 500; i++) { user = new User(); user.setId("test" + i); user.setName("name" + i); user.setDelFlag("0"); mapper.insert(user); } sqlSession.commit(); long end = System.currentTimeMillis(); System.out.println("---------------" + (start - end) + "---------------"); } |
②xml配置
<insert id="insert"> INSERT INTO t_user (id, name, del_flag) VALUES(#{id}, #{name}, #{delFlag}) </insert> |
第二種:mybatis BATCH模式插入
①junit類
@Test public void testInsertBatch2() throws Exception { long start = System.currentTimeMillis(); User user; SqlSession sqlSession = sqlSessionTemplate.getSqlSessionFactory().openSession(ExecutorType.BATCH, false);//跟上述sql區別 UserDao mapper = sqlSession.getMapper(UserDao.class); for (int i = 0; i < 500; i++) { user = new User(); user.setId("test" + i); user.setName("name" + i); user.setDelFlag("0"); mapper.insert(user); } sqlSession.commit(); long end = System.currentTimeMillis(); System.out.println("---------------" + (start - end) + "---------------"); } |
②xml配置與第一種②中使用相同
第三種:foreach方式插入
①junit類
@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) + "---------------"); } |
②xml配置
<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> |
nested exception is com.mysql.jdbc.PacketTooBigException: Packet for query is too large (5677854 > 1048576). You can change this value on the server by setting the max_allowed_packet' variable. |
第一種 | 第二種 | 第三種 | |
500條 | 7742 | 7388 | 622 |
1000條 | 15290 | 15078 | 746 |
5000條 | 78011 | 177350 | 1172 |
10000條 | 397472 | 201180 | 1205 |