mybatis 批量插入list对象集合

针对数据库使用oracle数据库:

第一种:开始设计id用的是数据库的 SEQUENCE 

mybatis如下:

<insert id="insertBatchOrderDetails" parameterType="java.util.List">

    insert into wms_inbound (ID,INBOUND_CODE)
    SELECT 
        SEQ_ORDER_DETAILS.NEXTVAL,A.* FROM(
  <foreach collection="list" item="item" index="index" separator="union all">
    select #{item.orderCode,jdbcType=VARCHAR}, #{item.orderHawbcode,jdbcType=VARCHAR} from dual 
 </foreach>) A
</insert>

 
执行的sql我单独拿出来在plsql执行了下,耗时:

第二种:几乎和第一种一样

<insert id="insertBatchOrderDetails" parameterType="java.util.List">

    insert into wms_inbound (ID,INBOUND_CODE) 
select * from(
  <foreach collection="list" item="item" index="index" separator="union all">
      select
        #{item.id,jdbcType=VARCHAR}, #{item.inboundCode,jdbcType=VARCHAR}
      from dual
  </foreach>)
</insert>

这种方式和第一种几乎一样,耗时:


第三种:在java代码里,其中

wmsInboundMapper.insert调用的是mybatis自动生成的单条插入方法
@Autowired
private SqlSessionTemplate sqlSessionTemplate;
public int saveBatch(List<WmsInbound> wmsInbounds){
		SqlSession session = sqlSessionTemplate.getSqlSessionFactory().openSession(ExecutorType.BATCH,false);

		int size = 10000;
		int result=0;
		try{
			for(int i = 0; i < wmsInbounds.size(); i++) {
				wmsInboundMapper.insert(wmsInbounds.get(i));
				result++;
				if(i % 1000 == 0 || i == size - 1) {
					//手动每1000个一提交,提交后无法回滚
					session.commit();
					//清理缓存,防止溢出
					session.clearCache();
				}
			}
		} catch (Exception e) {
			//没有提交的数据可以回滚
			session.rollback();
		} finally{
			session.close();
		}
		return result;
	}

执行时间为,4.5秒,:


传入集合为:list<对象>



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值