使用Mybatis框架批量插入的3种方法:多次调用insert方法、foreach标签、batch模式

一、 多次调用insert方法

	每插入一条数据都调用一次insert方法,这种方法适用于数据量小时使用,频繁使用会浪费数据库资源。

二、 foreach标签

	一次存入多条数据,使用方法如下:
	<insert id="insert1" keyColumn="goods_id" keyProperty="goodsId" parameterType="com.shop.test.pojo.entity.test"
            useGeneratedKeys="true">
        	insert into test (shop_id, test_type_id,)
       		 values
        	<foreach collection="record" item="item" separator="," >
            	(#{item.shopId,jdbcType=BIGINT}, #{item.goodsTypeId,jdbcType=BIGINT})
        	</foreach>
    </insert>`

三、 batch模式

	一次存入多条数据,使用方法如下:
	xml代码:
	<insert id="insert" keyColumn="goods_id" keyProperty="goodsId" parameterType="com.shop.test.pojo.entity.test"
            useGeneratedKeys="true">
        insert into test (shop_id, test_type_id)
        values 
        (#{shopId,jdbcType=BIGINT}, #{goodsTypeId,jdbcType=BIGINT})
    </insert>

后端java代码:

//先引入
 @Resource
 private SqlSessionFactory sqlSessionFactory;
 //具体实现
SqlSession sqlSession=sqlSessionFactory.openSession(ExecutorType.BATCH);
        List<test> insertlist=new ArrayList<>();
        test test1=new test((long)1,(long)12);
        for(int i=0;i<100000;i++){
            insertlist.add(test1);
        }
        try{
            Long mm=System.currentTimeMillis();
            TestDao mapper=sqlSession.getMapper(TestDao.class);
            insertlist.stream().forEach(e->{
                mapper.insert(e);
            });
            sqlSession.clearCache();
            sqlSession.commit();
        }catch(Exception e){
            System.out.println(e);
        }finally{
            sqlSession.close();
        }

四、三种方法比较

	1)insert
		适用于少量数据插入,每次使用都要调用数据库连接,频繁使用会浪费资源,效率低
	2)foreach标签
		使用foreach可以减少数据库连接的调用,效率比inser高
	3)batch模式
		当数据特别多时效率比foreach标签高

更多推荐

Mybatis批量插入