当前位置:网站首页>typeorm 批量插入数据优化和插入冲突操作
typeorm 批量插入数据优化和插入冲突操作
2022-08-09 13:26:00 【祥仔先生】
d本文主要记录一下批量插入数据的优化。
一、批量插入
首先能实现批量插入在typeorm中有save、insert和createQueryBuilder 这三种都可以。
根据官网上介绍的
You can create INSERT queries using QueryBuilder. Examples:
await dataSource
.createQueryBuilder()
.insert()
.into(User)
.values([
{ firstName: "Timber", lastName: "Saw" },
{ firstName: "Phantom", lastName: "Lancer" },
])
.execute()
This is the most efficient way in terms of performance to insert rows into your database. You can also perform bulk insertions this way.
这是一个非常搞笑的批量插入。但是我们发现如果我插入500条数据还会在操作日志中,还有跟着500条select 查询对应插入数据的id。加入我们不需要这个id的话 我们是可以关闭这个select的
entityManager
.createQueryBuilder()
.insert()
.into("user")
.values(users)
.updateEntity(false)
.execute();或者save操作的时候增加参数{ reload: false }。
二、插入如果出现冲突的操作
有的时候在并发情况下插入数据会出现Duplicate entry '6' for key 'PRIMARY 主键冲突。
当然了 如果加分布式锁也会有一定影响。
- 加分布式锁也可能会影响消费者的消息处理速度。
- 消费者依赖于redis,如果redis出现网络超时,我们的服务就悲剧了。
如果对业务影响不是很大的话 可以考虑使用下面的语句。
await connection.createQueryBuilder()
.insert()
.into(Post)
.values(post2)
.onConflict(`("id") DO NOTHING`)
.execute();
await connection.createQueryBuilder()
.insert()
.into(Post)
.values(post2)
.onConflict(`("id") DO UPDATE SET "title" = :title`)
.setParameter("title", post2.title)
.execute();对应的sql语句
INSERT INTO table (column_list)
VALUES (value_list)
ON DUPLICATE KEY UPDATE c1 = v1, c2 = v2,...;边栏推荐
猜你喜欢

Jetpack Compose - the use of Image (picture)

利用信号灯和共享内存实现进程间同步通信

RobotFramework 之 Setup和Teardown

华为ensp静态路由、DHCP

响应式pbootcms模板外贸灯具类网站

Row of openharmony container components

Mysql seven connection query methods

RobotFramework 之 库与关键字

C语言中的 递归问题 以及将递归改写成非递归。(解析常见的几个递归题目及代码) 求阶乘、求斐波那契、汉诺塔、

Jetpack Compose——Modifier的基本属性简单介绍
随机推荐
pytest 筛选用例
openharmony容器组件之Row
企业公众号开通微信支付
C语言 交换两个变量(不创建临时变量) 代码详解
音频基础学习——声音的本质、术语与特性
Sql之各种Join
Jetpack Compose - simply the basic attributes of Modifier is introduced
RobotFramework 之 资源文件
富媒体在客服IM消息通信中的秒发实践
tensorflow图片编码处理基础
【翠花学习单例模式】项目框架升级之单例模式及统一异常处理
Operating system migration practice deploying MySQL database on openEuler
三种ThreadLocal,玩转线程变量保存与传递
ensp如何正确配置静态路由
flink并行度知识点
Mysql seven connection query methods
Jetpack Compose——Modifier的基本属性简单介绍
FFmpeg av_interleaved_write_frame错误
开源一夏│别逗,作为程序员你竟还没参与过开源项目?
禁止输入(×),按键精灵小程序,快速上手