Mybatis批量插入

本文介绍了Mybatis中批量插入数据的三种方法:多次调用insert、使用foreach标签和batch模式。对于小量数据,可选择多次调用;中等数据量时,foreach标签较为适用;大量数据插入时,batch模式效率最高。通过实例代码详细解析了每种方法的实现过程。
摘要由CSDN通过智能技术生成

使用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标签高
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值