Mybatis批处理、Mysql深分页

一、Mybatis批量操作

1、Foreach方式

会拼接成:insert into table (ID, PHONE,MESSAGE) values (?,?,?), (?,?,?), (?,?,?)

当数据过多时,可能生成的动态sql过大,mysql默认仅1M的sql字符串,过长可能会执行失败。

在sql循环时设置batch与否其实执行时间差别不是很大,所以其实如果不是特别要求性能,可直接在sql中使用for循环即可。

实践发现,当表的列数较多(超过20),以及一次性插入的行数较多(上万条)时,插入性能非常差,通常需要20分钟以上

XML 复制代码
<insert id="saveBatch" parameterType="java.util.List">
    insert into mytable (id, name, sex, age) values
    <foreach collection="list" item="item" separator=",">
        (#{item.id}, #{item.name}, #{item.sex}, #{item.age})
    </foreach>
</insert>

2、ExecutorType.BATCH插入

Mybatis内置的ExecutorType有3种,SIMPLE、REUSE、BATCH;

默认的是simple,该模式下它为每个语句的执行创建一个新的预处理语句,单条提交sql;

batch模式重复使用已经预处理的语句,且批量执行所有更新语句,

但batch模式也有自己的问题,在Insert操作时,没提交事务前,无法获取到自增的id。

java 复制代码
public enum ExecutorType {
  SIMPLE, //mybatis的默认执行器,它为每个语句的执行创建一个新的预处理语句
  REUSE,  //会复用预处理语句
  BATCH   //会批量执行所有更新语句,不需要对同样的SQL进行多次预编译 ArticleCategory
}
public void saveBatch(List list) {
  SqlSession sqlSession = sqlSessionTemplate.getSqlSessionFactory().openSession(ExecutorType.BATCH, false);
    try {
        MyMapper mapper = sqlSession.getMapper(MyMapper.class);
        mapper.saveBatch(list);
        sqlSession.commit();
        sqlSession.clearCache();
    } catch (Exception e) {
        sqlSession.rollback();
        e.printStackTrace();
    } finally {
        sqlSession.close();
    }
}

二、Mysql深分页

1、普通分页

sql 复制代码
select * from table order by id limit m,n;

2、先查出主键,通过主键关联,支持跨页,减少回表。

sql 复制代码
select * from table as a
inner join (select id from table order by id limit m, n) as b
on a.id = b.id order by a.id;

3、取上一页最大主键做判断,不支持跨页插叙。

sql 复制代码
select * from table where id > #max_id# order by id limit 10, 10;

4、先查出主键,通过主键做范围判断,支持跨页,减少回表。

sql 复制代码
select * from table where id > (select id from table order by id limit m, 1) limit n;
相关推荐
工业甲酰苯胺9 分钟前
spring-事务管理
数据库·sql·spring
全栈前端老曹23 分钟前
【Redis】Redis 持久化机制 RDB 与 AOF
前端·javascript·数据库·redis·缓存·node.js·全栈
李慕婉学姐40 分钟前
Springboot平安超市商品管理系统6sytj3w6(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
数据库·spring boot·后端
Elastic 中国社区官方博客40 分钟前
易捷问数(NewmindExAI)平台解决 ES 升级后 AI 助手与 Attack Discovery 不正常问题
大数据·运维·数据库·人工智能·elasticsearch·搜索引擎·ai
瀚高PG实验室1 小时前
数据库意外中止,无法启动
数据库·瀚高数据库
gAlAxy...1 小时前
MyBatis-Plus 核心 CRUD 操作全解析:BaseMapper 与通用 Service 实战
java·开发语言·mybatis
Amarantine、沐风倩✨2 小时前
列表接口严禁嵌套 LISTAGG + REGEXP:一次 mission_label 性能事故复盘
java·数据库·sql
好好研究2 小时前
MyBatis - Plus(二)常见注解 + 常见配置
数据库·spring boot·mybatis·mybatis plus
PD我是你的真爱粉2 小时前
MySQL基础-DQL语句与多表查询
数据库·mysql
C#程序员一枚2 小时前
SqlServer如何创建全文索引
数据库·sqlserver