大家好,我是一安,之前有介绍《MySql批量插入数据三种方式性能对比》,当使用foreach要插入的数据量很大时,就会产生一个很长的SQL,但是MySQL有一个限制最大长度,如果超过最大长度程序会报异常Packet for query is too large
,并且过大也会影响插入性能。
要解决这个问题有两种方案:一是设置mysql的最大长度;二是对数据进行分片,也就是对list分片
小编这里推荐使用第二种,那常用的list分片,你会几种?下面介绍几种常见的:
伪代码
1.引入依赖
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.7.14</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>31.0.1-jre</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.4</version>
</dependency>
2.测试验证
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
for(int i=0;i<20;i++){
list.add(i);
}
//1.最基础的利用subList(),比如每批取3个
int count = list.size()/3;
for(int j = 0;j<=count;j++){
if(j==count){
System.out.println(list.subList(j*3,list.size()));
}else{
System.out.println(list.subList(j*3,(j+1)*3));
}
}
System.out.println("subList============================");
//2.利用Guava
//Guava是一种基于开源的Java库,Google Guava源于2007年的"Google Collections Library"。
//这个库是为了方便编码,并减少编码错误。这个库用于提供集合,缓存,支持原语句,并发性,常见注解,字符串处理,I/O和验证的实用方法
List<List<Integer>> newList = Lists.partition(list, 3);
newList.forEach(System.out::println);
System.out.println("Guava============================");
//3.利用Apache的commons
//包含了一些Apache开发的集合类,功能比 java.util. 强大
List<List<Integer>> newList2 = ListUtils.partition(list, 3);
newList2.forEach(System.out::println);
System.out.println("commons============================");
//4.利用hutool
//HuTool是一个小而全的Java工具类库,通过静态方法封装,降低相关API的学习成本,提高工作效率,它涵盖了Java开发底层代码中的方方面面
// List<List<Integer>> newList3 = ListUtil.split(list,3);
List<List<Integer>> newList3 = ListUtil.partition(list,3);
newList3.forEach(System.out::println);
System.out.println("hutool============================");
}
[0, 1, 2]
[3, 4, 5]
[6, 7, 8]
[9, 10, 11]
[12, 13, 14]
[15, 16, 17]
[18, 19]
subList============================
[0, 1, 2]
[3, 4, 5]
[6, 7, 8]
[9, 10, 11]
[12, 13, 14]
[15, 16, 17]
[18, 19]
Guava============================
[0, 1, 2]
[3, 4, 5]
[6, 7, 8]
[9, 10, 11]
[12, 13, 14]
[15, 16, 17]
[18, 19]
commons============================
[0, 1, 2]
[3, 4, 5]
[6, 7, 8]
[9, 10, 11]
[12, 13, 14]
[15, 16, 17]
[18, 19]
hutool============================
总结
小编这里推荐使用第三方,不使用subList,这种需要你手动计算和遍历,相对其他比较麻烦。后面会抽空做一期Guava,hutool介绍,其封装了很多实用的工具类,极大的方便了编码,并减少编码错误
号外!号外!
如果这篇文章对你有所帮助,或者有所启发的话,帮忙点赞、在看、转发、收藏,你的支持就是我坚持下去的最大动力!
SpringBoot整合ElasticJob实现分布式任务调度
原文始发于微信公众号(一安未来):MyBatis批量插入大批量数据 数据过多问题
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/44700.html