mybatis之使用foreach来进行批量插入数据

MyBatis批量插入几千条数据慎用foreach     近日,项目中有一个耗时较长的Job存在CPU占用过高的问题,经排查发现,主要时间消耗在往MyBatis中批量插入数据。mapper configuration是用foreach循环做的,差不多是这样。(由于项目保密,以下代码均为自己手写的demo代码) <insert id="batchInsert" parameterType="java.util.List"> ... 阅读详情

1、数据库为MySQL的情况下的sql语句为:

<insert id="insertAll" parameterType="com.scau.mybatis.entity.Sale">
    insert into t_sale values
    <foreach collection="saleList" item="sale" separator=",">
        (#{sale.year},#{sale.quarter},#{sale.number})
    </foreach>
</insert>

 

Mybatis插入大量数据效率对比:foreach插入、SqlSession批量插入、sql插入 sql插入的效率最高,sqlsession次之,mybatis框架foreach插入效率最低。执行效率echarts图:来源:blog.csdn.net/chenping1993/自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。深知大多数Java工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但对于培训机构动则几千的学费,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前! 阅读详情

相关推荐

Mybatis插入大量数据效率对比:foreach、SqlSession批量、sql

System.out.println(“xmlInsert 批量插入耗时:”+(System.currentTimeMillis()-start));System.out.println(“forEachInsert 插入开始========”);System.out.println(“xmlInsert 批量插入开始========”);System.out.println(“sql 插入开始========”);xml 插入mapper文件。//sql插入相关类。

2401_84181975的博客 1166

Mybatis中的foreach循环——循环插入多条数据

mybatis中的循环标签

a498936289的博客 4746

mybatis 利用foreach insert 批量插入数据

"insertAll" parameterType="List"> INSERT INTO oa_notify_record( ID, OA_NOTIFY_ID, USER_ID, READ_FLAG, READ_DATE ) if

hjh908778的博客 1625

Mybatis 批量插入数据 SQL

上面代码中在 SQL 语句的最外层使用了 for 循环,好处是将 List 类型的集合传递来写入数据时可以有的是新增有的是修改,例如3行数据,第一三行由于主键字段对应属性 sid 被设置为 NULL ,会向数据库中新增行,第二行数据设置了 sid ,并且该值在数据库中有对应行,那么会修改数据库中的该行上的数据。通过在 java 中测试,发现上面的语句新增一行成功后会返回1,修改成功后会返回2(这里有疑惑,如果清楚原因的麻烦跟帖科普下)。这种写法适合插入数据的项不变,

zzhongcy的专栏 4654

FPGA图像处理入门 ZYNQ7020 图像中值膨胀腐蚀滤波

图像处理的三种滤波 中值滤波应用较为广泛 综合膨胀和腐蚀可以实现边缘检测。

Coast_的博客 732

C#与AutoCAD插件开发实战:从零构建你的第一个自定义命令

本文为AutoCAD插件开发新手提供了一份完整的C#实战指南。从搭建Visual Studio开发环境、添加AutoCAD .NET API引用,到编写并注册第一个“Hello AutoCAD”自定义命令,再到实现一个交互式绘制十字线的实用命令,详细讲解了核心代码结构与调试技巧。文章旨在帮助工程师和设计师利用C#自动化重复绘图任务,显著提升工作效率。

weixin_29294597的博客 445

Mybatis中foreach动态添加数据

&lt;insert id="addUser" parameterType="com.yizhi.app.model.User"&gt;  insert into  &lt;include refid="user"/&gt;  (  &lt;include refid="column"/&gt;  )  values  &lt;foreach collect

m0_37846887的博客 2351

InfiniBand(IB)实战指南:从硬件配置到性能优化

本文是一份详尽的InfiniBand实战指南,涵盖从硬件选型、部署到驱动配置、性能优化的全流程。重点解析了InfiniBand作为AI训练与高性能计算(HPC)核心网络的优势,特别是其支持的RDMA技术如何实现微秒级低延迟。文章提供了硬件匹配、NCCL压测、内核参数调优及在PyTorch分布式训练中启用IB的实操步骤,旨在帮助工程师构建和优化高性能计算集群。

mqtt6iot的博客 592

Mybatis动态SQL之foreach标签批量插入数据(MySQL版)

我们在MySQL中可以使用foreach标签进行批量插入数据。 foreach中可以有两种方式批量插入数据: 方式1: INTERT INTO TableName Values(值1,值2,值3….),(值1,值2,值3….)…. 方式2: INTERT INTO TableName Values(值1,值2,值3….);INTERT INTO TableName Values...

u014268482的博客 1万+

Springboot项目中使用邮箱验证码注册登录的代码实现

本文介绍了在Spring Boot应用中实现邮箱验证码注册和登录功能的完整方案。文章首先概述了三种用户认证方式(邮箱验证码注册/登录和传统密码登录),然后详细说明了实现所需的技术栈(Spring Boot、Spring Security、JWT等)。重点阐述了邮件服务配置、验证码生成与存储的核心实现,包括QQ邮箱授权码获取、Thymeleaf邮件模板处理以及验证码缓存管理。最后展示了发送验证码和用户注册的API实现,为开发者提供了完整的参考方案。该方案兼顾安全性和用户体验,适合现代Web应用的用户认证需求。

BXCQ_xuan的技术专栏 | 实战干货·实践教程·学习笔记 1351

Unity游戏开发实战:用Flow Field实现RTS百人军团流畅寻路(附完整代码)

本文深入探讨了在Unity中利用流场寻路技术解决RTS游戏大规模单位移动性能瓶颈的实战方案。通过解析从Dijkstra算法生成成本场、积分场到最终向量场的核心原理,并结合分块、缓存及与DOTS/ECS架构集成的优化策略,实现了百人军团的流畅群体寻路。文章提供了完整的代码示例,助力开发者构建高性能的RTS寻路系统。

weixin_28363123的博客 595

MyBatis最佳实践

第一种简单方法,就是传入参数(或者包装Page对象)实现SQL语句翻页,业务需要额外代码计算起止序号,SQL语句需要添加分页处理存在代码冗余。MyBatis动态标签批量操作存在一定缺点,比如数据量特别大拼接SQL语句过大,导致超过MySQL服务端接收数据包大小限制异常,不过可以通过修改默认配置项,或者手动控制数据条数解决。业务数据经常会遇到关联查询情况,比如查询员工就会关联部门(一对一),查询学生成绩就会关联课程(一对一),查询订单就会关联商品(一对多)。很明显,如果数据量很大,这种翻页方式效率会很低。

2401_89221445的博客 1055

YOLOv8有效改进系列及项目实战目录 包含卷积,主干 注意力,检测头等创新机制 以及 各种目标检测分割项目实战案例

大家好!欢迎阅读本专栏。本专栏涵盖了YOLO8中C2f、主干网络、检测头、注意力机制、Neck等多种结构的创新,同时也包括了 YOLO相关的基础知识以及相关项目。

专注于图像领域,主要研究内容包括计算机视觉和深度学习,特别是在图像分类、目标检测和图像生成等方面有深入的研究和实践经验。 3万+

Mybatis使用Foreach批量插入MySQL数据

Mybatis使用批量插入MySQL数据 Mysql的insert语句: # 方式一: insert into 表名(列名,...) values(值1,...); # 方式二: insert into 表名 set 列名=值,列名=值,... # 批量 INSERT INTO beauty VALUES(23,'小白1','女','1990-4-23','1898888888',NULL,2) ,(24,'小白2','女','1990-4-23','1898888888',NULL,2) ,(25,'小白

CodeWhite 3886

Experion PKS系列开发:I_O模块_ExperionPKS与第三方I-O模块的集成

通过上述步骤,可以成功将第三方I/O模块集成到Honeywell Experion PKS系统中,实现对现场设备的监视和控制。集成过程中需要注意选择合适的第三方模块,配置正确的通信参数,编写正确的控制逻辑,并进行充分的测试,以确保系统的稳定性和可靠性。不同的通信协议(如Modbus、Profibus、Ethernet/IP、CANopen、OPC UA)有其独特的配置和编程方法,但总体流程相似。在实际应用中,根据项目需求选择合适的协议和模块,可以有效提高系统的灵活性和适应性。

zhubeibei168的博客 1117

零基础学习CANoe Panel(17)—— Panel CAPL Function

CANoe内置了几个CAPLFunction,允许我们在CAPL运行时动态的更改Panel控件的属性,比如打开某个panel,禁用某个控件,更改控件颜色等。

蚂蚁小兵 3551

myBatis使用foreach批量插入数据

INSERT INTO lt_product_city (product_id, city_id) VALUES (#{product_id}, #{bookCity})

plutoma的专栏 9214

深度学习工具包 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")

MyBatis中批量插入数据,多重forEach循环

在业务开发过程中,遇到批量插入时,需要进行多重forEach循环的情况。下面是一个实际应用: public class SysRoleData extends DataEntity&lt;SysRoleData&gt; { private static final long serialVersionUID = 1L; private String kind; /...

m0_37837382的博客 2万+

IMSL CNL 7.0.0 (x86-64)Crack

IMSL CNL 7.0.0 (x86-64)Crack intel的算法库破解文件,这是C++版本的破解文件

inori mmd 7z

楪祈的模型资源....................................................................................................................................................................................................................

MyBatis使用Foreach批量插入数据

## MySQL批量插入(效率较低) <insert id="saveBatch"> <foreach collection="list" item="item" separator=";"> INSERT INTO student (name, age, id) VALUES (#{item.name},#{item.age},#{item.id}) </foreach> </insert> ## MySQL批量插入(效率较高) <

weixin_40460171的博客 2557

ET2012新版免狗免安装绿色软件

ET2012新版免狗免安祖昂绿色软件。,新界面,新视觉,

MyBatis foreach语句批量插入数据

项目框架:Spring+SpringMVC+MyBatis+Oracle 问题描述:需要将程序里的一个集合保存到数据库里,集合的类型对应数据库的一个实体,若在程序里遍历集合再一条条保存到数据库表中有点麻烦,这里可以利用MyBatis 的 foreach标签实现批量插入数据。 实例: 要新增的实体为Item(项目实体):

语文课 1万+

MyBatis批量插入数据时,一定要考虑慎用foreach

来源:blog.csdn.net/huanghanqian/article/details/83177178近日,项目中有一个耗时较长的Job存在CPU占用过高的问题,经排查发现,主要时间...

独行侠梦的博客 1420

mybatis双层foreach循环,批量插入数据 -oracle

当遇到表较多和字段较多的情况时,为了便捷开发,可在foreach标签中采用了第二层的foreach循环。通过内层循环调用外层循环中的map,通过获取map中的key获取字段名称,以及通过key获取value,实现数据的批量操作;

weixin_43882190的博客 3517

MyBatis批量插入上万条数据慎用ForEach

在我们的项目中,会不停地使用批量插入这个方法,而因为MyBatis对于含有的语句,无法采用缓存,那么在每次调用方法时,都会重新解析sql语句。所以,如果非要使用foreach的方式来进行批量插入的话,可以考虑减少一条insert语句中values的个数,最好能达到上面曲线的最底部的值,使速度最快。没有问题,但是经过项目实践发现,当表的列数较多(20+),以及一次性插入的行数较多(5000+)时,整个插入的耗时十分漫长,达到了14分钟,这是不能忍的。...

朱昶伟 1483

Mybatis Batch模式和foreach标签批量插入数据效率对比

Mybatis批处理效率 前言: 搭建mybatis测试环境 application.yml 注意: url后面必须加上 rewriteBatchedStatements=true 才能开启batch模式 # 数据源配置 spring: datasource: driverClassName: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncodi

qq_41501190的博客 3023
上一篇: springboot 2.x整合rabbitmq之使用自定义Listener
下一篇: sprinCloud学习之搭建Eureka Server集群
adminit
博客等级 码龄10年 1粉丝 21原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值
⌂ 换网址