1. 程式人生 > 其它 >Mybatis 批量插入資料的三種方式

Mybatis 批量插入資料的三種方式

1.for迴圈insert

 long start = System.currentTimeMillis();
    for(int i = 0 ;i < 100000; i++) {
        User user = new User();
        user.setId("id" + i);
        user.setName("name" + i);
        user.setPassword("password" + i);
        userMapper.insert(user);
    }
    long end = System.currentTimeMillis();
    System.out.println("---------------" + (start - end) + "---------------");
  •  
    <insert id="insert">
      INSERT INTO t_user (id, name, password)
          VALUES(#{id}, #{name}, #{password})
    </insert>
  •  

時間為380826ms

2.Mybatis batch模式

  SqlSession sqlSession = sqlSessionTemplate.getSqlSessionFactory().openSession(ExecutorType.BATCH, false);//跟上述sql區別
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

        long start = System.currentTimeMillis();
        for (int i = 0; i < 100000; i++) {
            User user = new User();
            user.setId("id" + i);
            user.setName("name" + i);
            user.setPassword("password" + i);
            userMapper.insert(user);
        }
        sqlSession.commit();
        long end = System.currentTimeMillis();
        System.out.println("---------------" + (start - end) + "---------------");
  •  
   <insert id="insert">
      INSERT INTO t_user (id, name, password)
          VALUES(#{id}, #{name}, #{password})
    </insert>
  •  

時間為203660ms

3.批量foreach插入

   long start = System.currentTimeMillis();
        List<User> userList = new ArrayList<>();
        for (int i = 0; i < 100000; i++) {
            User user = new User();
            user.setId("id" + i);
            user.setName("name" + i);
            user.setPassword("password" + i);
            userList .add(user);
        }
        userMapper.insertBatch(userList);
        long end = System.currentTimeMillis();
        System.out.println("---------------" + (start - end) + "---------------");
  •  
<insert id="insertBatch" parameterType="java.util.List">
        INSERT INTO t_user
        (id, name, password)
        VALUES
        <foreach collection ="userList" item="user" separator =",">
            (#{user.id}, #{user.name}, #{user.password})
        </foreach >
</insert>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

時間為8706ms

插入三種方式,文章參考:https://segmentfault.com/a/1190000021290975?utm_source=tag-newest

如果批量增加資料量較多時 建議採用batch模式,foreach一次性插入資料量建議10-100條,for迴圈是最不建議的方式,需要頻繁的建立關閉資料庫連線,比較耗時。