LockModeType.PESSIMISTIC_WRITE 对于 JPA 中的 UPSERT 是否足够?
我读过这篇关于 JPA 并发的文章,但要么是我太厚了,要么是不够明确。
我希望执行数据库控制的原子 update-if-found-else-insert 操作(UPSERT
)。
在我可怜的迟钝大脑看来,我可以——当然是在一个事务内——运行一个锁定模式为“PESSIMISTIC_WRITE”的命名查询,看看它是否返回任何结果,然后是 persist()
或 update()
。
我不清楚的是使用 PESSIMISTIC_WRITE
锁与使用 PESSIMISTIC_READ
锁执行此操作之间的区别。我读过这些句子 - 我明白 PESSIMISTIC_READ
是为了防止不可重复读取,而 PESSIMISTIC_WRITE
是......好吧,也许我不明白非常好:-) - 但其底层只是一个 SQL SELECT FOR UPDATE
,是吗?在这两种情况下?
I've read this article on JPA concurrency, but either I am too thick or it is not explicit enough.
I am looking to do a database-controlled atomic update-if-found-else-insert operation (an UPSERT
).
It looks to my poor slow brain that I can--within a transaction of course--run a named query with a lock mode of PESSIMISTIC_WRITE
, see if it returns any results, and then either a persist()
or an update()
afterwards.
What I am not clear on are the differences between doing this operation with a PESSIMISTIC_WRITE
lock vs. a PESSIMISTIC_READ
lock. I've read the sentences--I understand that PESSIMISTIC_READ
is intended to prevent non-repeatable reads, and PESSIMISTIC_WRITE
is...well, maybe I don't understand that one so well :-) --but underneath it's just a SQL SELECT FOR UPDATE
, yeah? In both cases?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我可能没有完全回答整个问题,但如果您想在没有任何竞争条件的情况下实现上述内容,那么在我看来,您需要一个表级独占模式锁定(不仅仅是行)。不知道JPA能不能实现这个功能。也许您可以澄清什么对您来说是可以接受的。
I'm maybe not answering exactly the whole question but if you want to implement the above without any race condition, you need IMO a table-level LOCK IN EXCLUSIVE MODE (not only rows). I don't know if this can be done with JPA. Maybe you could clarify what would be acceptable for you.
我曾经遇到过这样的情况,并发现:
链接 读取或写入文章
I have faced this kind of situation and found this:
link to the article
在重复键上插入.. UPDATE
就是这样做的。INSERT .. ON DUPLICATE KEY UPDATE
does that.