Mybatis批量新增
生活随笔
收集整理的這篇文章主要介紹了
Mybatis批量新增
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
文章目錄
- 前言
- 一、For each標簽
- 1、Mapper.xml
- 2、Mapper.interface
- 3、controller.class
- 4、運行結果
- 二、基于Session的Executor Type方式
- 1.Mappler.xml
- 2、在controller調(diào)用
- 3、運行結果
- 總結
前言
批量插入的使用背景現(xiàn)實中應該會用到很多很多,但哪種方式效率才是最高的呢?以下內(nèi)容僅代表個人觀點。不喜勿噴
mybatis的批量新增有兩種方式,mybatis的foreach標簽,基于Session的Executor Type方式。
一、For each標簽
這里我們只講代碼,并不具體搭建工程,不明白的小伙伴可以去我博客查看關于springboot的文章。
1、Mapper.xml
<insert id="batchSaveUser" parameterType="java.util.List">insert into user(username,password,address,sex,age,imgPath) values<foreach collection="list" item="user" separator=",">(#{user.username},#{user.password},#{user.address},#{user.sex},#{user.age},#{user.imgPath})</foreach></insert>2、Mapper.interface
Integer batchSaveUser(List<User> list);3、controller.class
long startSave1 = System.currentTimeMillis();ArrayList<User> users = new ArrayList<>();for (Integer i = 0; i < 1000000; i++) {User user1 = new User();user1.setUsername("李白"+i);user1.setAge(i);user1.setSex(i%2==0?"男":"女");user1.setAddress("北京市朝陽區(qū)");user1.setImgPath("/static/202307-15784861870c53.jpg");users.add(user1);}long endSave1 = System.currentTimeMillis();System.out.println("裝載數(shù)據(jù)消耗:"+(endSave1-startSave1)/1000+"秒");long startSave = System.currentTimeMillis();userService.batchSaveUser(users);long endSave = System.currentTimeMillis();System.out.println("用時:"+(endSave-startSave)/1000+"秒");return "用時:"+(endSave-startSave)/1000+"秒";4、運行結果
可以看到消耗62秒,我運行了多次,平均都在一分鐘左右。
二、基于Session的Executor Type方式
1.Mappler.xml
創(chuàng)建一條insert語句即可。
<insert id="saveUser" parameterType="com.chenan.springboot_mybatis.pojo.User">insert into user(username,password,address,sex,age,imgPath) values(#{username},#{password},#{address},#{sex},#{age},#{imgPath})</insert>2、在controller調(diào)用
這里考慮到性能問題,分批次提交:
ArrayList<User> users = new ArrayList<>();for (Integer i = 0; i < 1000000; i++) {User user1 = new User();user1.setUsername("李白"+i);user1.setAge(i);user1.setSex(i%2==0?"男":"女");user1.setAddress("河北邯鄲");user1.setImgPath("/static/202307-15784861870c53.jpg");users.add(user1);}System.out.println("開始插入數(shù)據(jù)");long startSave = System.currentTimeMillis();SqlSession sqlSession = sqlSessionTemplate.getSqlSessionFactory().openSession(ExecutorType.BATCH);UserDao mapper = sqlSession.getMapper(UserDao.class);int t = 2000;int k = 0;if(users.size()%t == 0){k = users.size()/t;}else{k = users.size() / t + 1;}int num = 0;for (int j = 0; j < k; j++) {for (Integer i = 0; i < t; i++) {num = j*t+i;User user1 = users.get(num);mapper.saveUser(user1);if(i==(t-1)){sqlSession.commit();}}}sqlSession.close();long endSave = System.currentTimeMillis();System.out.println("用時:"+(endSave-startSave)/1000+"秒");return "";3、運行結果
可以看到,用了18分鐘左右,可以說相差了接近20倍
總結
我看過很多博客,毫無疑問,內(nèi)容大概都是第二種方式更快一些,所以我才來做的測試,但結果我很詫異,也許是我的使用方法有問題,但就目前來說,我更愿意用第一種方式,同時如果有小伙伴們知道原因出在哪里,歡迎溝通。
總結
以上是生活随笔為你收集整理的Mybatis批量新增的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: windows10 media play
- 下一篇: stata:应用stata学习计量经济学