Mybatis批量提交

MyBatis的性能优化——批量操作 批量操作是数据处理场景中的性能关键点,尤其在数据迁移、报表生成等大数据量场景下,优化效果可提升10倍以上性能。 阅读详情

有两种方式可以实现mybatis的批量提交,第一种便是foreach标签,第二种便是开始mybatis的批量模式。

一、通过foreach标签

foreach标签即是通过迭代传入的集合或者数组,进行拼接sql。

标签包含以下属性:

​ item:表示集合中每一个元素进行迭代时的别名

​ index:表示每次迭代到的位置

​ open:表示该语句以什么开始

​ separator:表示在每次进行迭代之间以什么符号作为分隔符

​ close:表示以什么结束

​ collection:表示要迭代的对象,可以是集合则属性值为list,也可以是数组则属性值为array

示例:

<insert id="batchInsert" parameterType="java.util.List">
    insert into person (
        id, `name`, age, phone, address, created_time, updated_time
    )
    values
    <foreach collection="list" item="item" index="index" separator=",">
    (
        #{item.id,jdbcType=BIGINT},
        #{item.name,jdbcType=VARCHAR},
        #{item.age,jdbcType=TINYINT},
        #{item.phone,jdbcType=VARCHAR},
        #{item.address,jdbcType=VARCHAR},
        #{item.createdTime,jdbcType=BIGINT},
        #{item.updatedTime,jdbcType=BIGINT}
    )
    </foreach>
</insert>

实际生成的sql是这样的:

insert into person ( id, `name`, age, phone, address, created_time, updated_time ) values ( ?, ?, ?, ?, ?, ?, ? ) , ( ?, ?, ?, ?, ?, ?, ? )

二、通过Mybatis的ExecutorType.BATCH方式

Mybatis内置的ExecutorType有3种,默认的是simple,该模式下它为每个语句的执行创建一个新的预处理语句,单条提交sql;而batch模式重复使用已经预处理的语句,并且批量执行所有更新语句,显然batch性能将更优;

批量提交只能应用于 insert, update, delete
这时我们手动控制事务。

示例:

@Autowired
private SqlSessionTemplate sqlSessionTemplate;

public void exeBatch() {
    //新获取一个模式为BATCH,自动提交为false的session
    SqlSession sqlSession = sqlSessionTemplate.getSqlSessionFactory().openSession(ExecutorType.BATCH, false);
    PersonModelMapper mapper = sqlSession.getMapper(PersonModelMapper.class);
    try {
        for (int i = 0; i < 10; i++) {
            //或者使用
            //sqlSession.insert("com.example.demo.db.dao.PersonModelMapper.insertSelective", new PersonModel());
            //主意这时候不能正确返回影响条数了
            mapper.insertSelective(new PersonModel());
        }
        sqlSession.commit();
        //清理缓存,防止溢出
        //sqlSession.clearCache();
    } catch (Exception e) {
        //异常回滚
        sqlSession.rollback();
    } finally {
        sqlSession.close();
    }
}
基于mybatis batch实现批量提交大量数据 主要介绍了基于mybatis batch实现批量提交大量数据,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 立即下载

相关推荐

MyBatis通过BATCH批量提交的方法

今天小编就为大家分享一篇关于MyBatis通过BATCH批量提交的方法,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧

MyBatis---BATCH批量提交数据

当需要更新数据库里大量数据时,可以用MyBatis里BATCH来批量提交数据,这样可以节省时间。

zhiwenganyong的博客 7921

红外与可见光融合避坑指南:LLVIP数据集实测6大算法效果对比

本文基于专为弱光视觉设计的LLVIP数据集,对GTF、DenseFuse、FusionGAN、IFCNN等6种主流红外与可见光图像融合算法进行了深度实测与对比。通过客观指标与可视化分析,揭示了算法在极端弱光下易出现特征丢失的共性问题,并探讨了融合图像对下游目标检测任务的实际增益,为工程选型与算法调优提供了实用指南。

weixin_29092031的博客 440

MyBatis 批量提交 - BATCH

很多人在用 MyBatis 或者 通用 Mapper 时,经常会问有没有批量插入和批量更新的方法。 实际上许多时候没必要用 &amp;amp;lt;foreach&amp;amp;gt; 去实现特别复杂的批量操作。直接通过 MyBatis 的 BATCH 方式执行增删改方法即可。 下面是一个批量用法的例子: @Autowired private SqlSessionFactory sqlSessionFactory...

偶尔记一下 - mybatis.io 2万+

【Niagara Vykon N4 】物联网学习 03照明控制及照明时间表

3.1 设计思路 3.2逻辑组件添加 ①依据原有控制照明逻辑,打开palette,找到schedule模块,添加BoolenSchedule。 ②打开kitContrl,找到Util,并添加BoolenSwitch。 ③剪切到原有的逻辑线,并进行逻辑连接,如下图。 ④新建BooleanWritable,命名为Switch,设置参数并进行逻辑连接,若下图。 3.3界面设计 ⑤至此完成了逻辑的设...

weixin_45217107的博客 2863

【Ultrascale+ MPSOC学习记录】10、PS端以太网使用lwip

还是参考ALINX教程,学习PS端以太网如何使用,从教程中可以看到,开发板使用了一个xilinx默认不支持的phy JL2121,所以需要修改lwip的库源码。

ryo891012的博客 882

MyBatis 通过 BATCH 批量提交

本文由 简悦 SimpRead 转码, 原文地址 https://www.jb51.net/article/153382.htm 很多人在用 MyBatis 或者 通用 Mapper 时,经常会问有没有批量插入和批量更新的方法。 实际上许多时候没必要用<foreach> 去实现特别复杂的批量操作。直接通过 MyBatis 的 BATCH 方式执行增删改方法即可。 下面是一个批量用法...

weixin_30565327的博客 990

群晖NAS实战:从零部署Container Manager与Docker代理配置全攻略

本文详细介绍了在群晖NAS上从零部署Container Manager与配置Docker代理的完整流程。针对国内用户常见的镜像拉取问题,提供了图形化界面与SSH命令行两种解决方案,并分享了MySQL容器部署的实战案例。文章特别强调了网络配置技巧和日常维护方法,帮助用户高效管理NAS上的容器应用。

weixin_29254673的博客 1308

java批量提交_MyBatis通过BATCH批量提交的方法

很多人在用 MyBatis 或者 通用 Mapper 时,经常会问有没有批量插入和批量更新的方法。实际上许多时候没必要用去实现特别复杂的批量操作。直接通过 MyBatis 的 BATCH 方式执行增删改方法即可。下面是一个批量用法的例子:@Autowiredprivate SqlSessionFactory sqlSessionFactory;@Transactional(rollbackFor ...

weixin_29011239的博客 1262

Vivado 18.3安装全攻略:从下载到配置的完整指南

本文详细介绍了Vivado 18.3的安装全流程,从下载准备到配置优化,特别适合FPGA开发者。文章包含硬件要求、版本选择、组件配置等实用技巧,帮助用户避免常见安装问题,确保稳定运行。重点解析了License配置和系统优化设置,提升开发效率。

weixin_28331555的博客 568

STM32中断实战:用ITR9606红外传感器DIY转速计数器(附完整代码)

本文详细介绍了如何使用STM32中断机制和ITR9606红外传感器DIY高精度转速计数器。从传感器选型、中断配置到抗干扰设计,提供完整的实战指南和优化代码,特别适合嵌入式开发者和硬件工程师快速实现工业级转速检测系统。

weixin_29159613的博客 290

mybatis 批量提交-提升效率

在 MyBatis 中进行批量提交,通常可以通过以下几种方式实现: ### 1. 使用。可以分批处理,比如list大小设置为1000条;的执行器类型来实现批量操作。MyBatis 提供了。

dzhou1991的博客 585

STM32 W5500 Freemodbus Modbus TCP协议功能实现

STM32F103VCT6 W5500(SPI1),实现Modbus-TCP协议的功能

坚韧与专注 2万+

mybatis-批量提交的实现

mybatis的BATCH 批量提交的实现代码参考 @Resource private SqlSessionTemplate sqlSessionTemplate; //批量插入 List<BeventInfoDetail> list = new ArrayList<BeventInfoDetail>(); for(int i =0; i < idsArray.length; i++) { //路况详情ID Long traff

peter_ou的博客 888

STM32入门教程:图像处理

然后,我们使用 STM32 的 DSP 模块中的 arm_mean_u8 函数计算原始图像的平均值,并将结果存储在 meanValue 变量中。然后,我们需要编写代码配置 STM32 的外部中断输入引脚,并在中断处理函数中读取 OV7670 摄像头模块输出的图像数据。然后,我们需要编写代码配置 STM32 的 USB OTG 接口,并在回调函数中读取 USB 摄像头输出的图像数据。一、图像采集 图像采集是图像处理的第一步,我们需要将外部图像源的数据导入到 STM32 中进行处理。

2401_85625565的博客 1616

Devexpress16.2.6破解工具

Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具

mybatis 批量提交清除缓存_Mybatis 扫盲

1. Java Jdbc 数据库操作过2. mybatis demo@Test public void testGetUserById() throws IOException { //1.创建SqlSessionFactoryBuilder对象 SqlSessionFactoryBuilder ssfb = new SqlSessionFactoryB...

weixin_42378997的博客 652

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Spring+Mybatis批量提交(batchUpdate)

Spring+Mybatis批量提交(batchUpdate) 目录Spring+Mybatis批量提交(batchUpdate)公共引入:SqlSessionFactory方式一:手动调动并提交方式二:自动调用并提交 提供两种批量提交方式,如有问题,欢迎网友随时指正 公共引入:SqlSessionFactory @Autowired private SqlSessionFactory sqlSessionFactory; 方式一:手动调动并提交 获取sqlSession对象 SqlSession s

瞳孔里的阳光 4708

锂电池充电器电路设计 里面有电路

锂电池充电器电路设计 里面有电路 3.7V升压到5V电路设计。

java 批量提交_基于mybatis batch实现批量提交大量数据

很多人在用 MyBatis 或者 通用 Mapper 时,经常会问有没有批量插入和批量更新的方法。实际上许多时候没必要用 去实现特别复杂的批量操作。直接通过 MyBatis 的 BATCH 方式执行增删改方法即可。下面是一个批量用法的例子:在xml文件配置多条参数同时插入:select SEQ_CTAS_SHARK_FLT.nextval as recId from dualinsert int...

weixin_34070493的博客 946

mybatis 批量提交

简介:mybatis的批量操作减少数据库连接次数 一、mapper 使用foreach 遍历   批量insert:    <insert id="addEmpsBatch"> INSERT INTO emp(ename,gender,email,did) VALUES <foreach collec...

388

mybatis batch批量提交大量数据

转载:https://blog.youkuaiyun.com/Java_Mr_Zheng/article/details/50476757 在xml文件配置多条参数同时插入: &lt;insert id="insertBatch2" parameterType="ctas.entity.SharkFlt"&gt; &lt;selectKey keyProperty="recId" order="B...

weixin_33694172的博客 1523

mybatis 开启批量提交

## 当我们在开发中,需要多次update或者insert,但是又想提高效率,这时可以用批量提交的方式。批量提交最常见的就是在mapper中使用fo foreach

qq_35134375的博客 1342

mybatis批量提交

之前在做项目时,使用mybatis,批量执行sql,这里简单写下步骤 在配置数据库连接时,加入一个参数,例如 jdbc:mysql://127.0.0.1:3307/mvs-report?allowMultiQueries=true 在mybatis执行时传入list集合参数, 在mybatis的xml文件中拼装sql,例如 <insert ...

weixin_30782331的博客 165

SpringBoot+Mybatis实现批量提交

把要插入的数据统一放到集合里面,再把数据传给数据库。在对应的mapper文件编写sql语句。缺点:频繁多次访问数据库 速度慢。

ZDrawer的博客 1123
上一篇: SpringBoot配置多数据源
下一篇: 单元测试之Mock模拟对Controller进行测试
淋雨一直走啊
博客等级 码龄11年 39粉丝 46原创
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值