Upsert与事务 [英] Upsert with a transaction

查看:118
本文介绍了Upsert与事务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Spring与PostgreSQL,我尝试做一个类型的UPSERT通过使用这样的代码:

  jt.update(delete from A where id = 1)
jt.update(insert into A(id,value)values(1,100))



包含在一个事务中(使用 @Transactional )。



问题是,当有许多并发请求时,这个代码失败,出现重复键错误,意味着事务不是孤立的,或...



我缺少关于事务如何工作的事情?我应该在这里使用不同的机制(例如线程同步)?

解决方案

我写了一个相当大的博客,虽然我可能会获得链接的投票,请阅读此< a>。



要点是事务在这里没有帮助(至少在默认情况下),虽然可以写正确的upsert,但它实际上很棘手。


I'm using Spring with PostgreSQL and I try to do a sort of UPSERT by using a code like this:

jt.update("delete from A where id = 1")
jt.update("insert into A (id, value) values (1, 100)")

wrapped inside a transaction (using @Transactional).

The problem is that, when there are many concurrent requests, this code fails with 'duplicate key' errors, meaning the transaction is not isolated, or...

Am I missing something about how transactions work? Should I use a different mechanism here (ex. thread synchronization)?

解决方案

I wrote a rather large blogpost about it, so even though I might get downvotes for links, read this.

The gist is that transactions do not help in here (at least by default), and while it is possible to write correct upsert, it's actually pretty tricky.

这篇关于Upsert与事务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆