mybatis+oracle的批量插入

本文详细介绍了使用MyBatis进行批量数据插入的优化方法,通过控制事务和分批提交来提高数据库操作效率。示例代码展示了如何设置批量插入的SQLSession,控制每批提交的数据量,以及具体的SQL语句结构。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

// 批量插入,手动控制事务
SqlSession batchSqlSession = null;
try {
    batchSqlSession = sqlSessionTemplate.getSqlSessionFactory()
        .openSession(ExecutorType.BATCH, false);// 获取批量方式的sqlsession
    int batchCount = 1000;// 每批commit的个数
    int batchLastIndex = batchCount - 1;// 每批最后一个的下标
    for (int index = 0; index < saveList.size();) {
        if (batchLastIndex > saveList.size()) {
            batchLastIndex = saveList.size();
            batchSqlSession.insert(
                "com.jomoo.oms.baseData.mapper.CapaCityMapper.create2",
                saveList.subList(index, batchLastIndex));
            batchSqlSession.commit();
            break;// 数据插入完毕,退出循环
        } else {
            batchSqlSession.insert(
                "com.jomoo.oms.baseData.mapper.CapaCityMapper.create2",
                saveList.subList(index, batchLastIndex));
            batchSqlSession.commit();
            index = batchLastIndex;// 设置下一批下标
            batchLastIndex = index + (batchCount - 1);
        }
    }
} catch (Exception e) {
    throw new OptException(e.getMessage());
} finally {
    batchSqlSession.close();
}
<insert id="create2"  parameterType="com.jomoo.oms.baseData.model.CapaCityModel">
    <selectKey keyProperty="id" order="BEFORE" resultType="Long">
        select JOMOO_OMS.OMS_CAPACITY_S.NEXTVAL as id from dual
    </selectKey>

    insert into JOMOO_OMS.OMS_CAPACITY(<include refid="Base_Column_List"></include>) select JOMOO_OMS.OMS_CAPACITY_S.NEXTVAL, A.*
    from (
    <foreach collection="list" item="capacity" index="index" open="" close="" separator="union all">
        select
        #{capacity.factoryCode},
        #{capacity.factoryName},
        #{capacity.productSeriesCode},
        #{capacity.productSeries},
        #{capacity.materialCode},
        #{capacity.materialName},
        #{capacity.dateNumber},
        #{capacity.totalCapacity},
        #{capacity.leftCapacity},
        #{capacity.remark},
        #{capacity.registerId},
        #{capacity.createdByEmployee},
        #{capacity.createdByDept},
        #{capacity.enableFlag},
        sysdate
        from dual
    </foreach>
    ) A
</insert>

转载于:https://www.cnblogs.com/mabaoqing/p/10691526.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值