使用 attachDirty (saveOrUpdate) 的休眠事务和并发 [英] Hibernate Transactions and Concurrency Using attachDirty (saveOrUpdate)

查看:33
本文介绍了使用 attachDirty (saveOrUpdate) 的休眠事务和并发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下情况,attachDirty saveOrUpdate() 总是尝试在突发调用事务性注释方法时保留实体.

I have the following case where attachDirty saveOrUpdate() always tries to persist the entities when the transactional annotated method is called in burst.

有没有办法避免这种违反主键约束的异常?我认为 saveOrUpdate() 会在实体尚未创建时持续存在,否则会更新它.

Is there a way to avoid this primary key constraint violation exception? I thought that saveOrUpdate() would persist if the entity is not yet created and update it otherwise.

我使用这个 ..orUpdate() 而不是 persist() 作为处理这些突发的一种方式.

I used this ..orUpdate() instead of persist() as a way to handle these bursts.

实际上没有数据损坏.因为第一个 saveOrUpdate() 确实根据需要为每个实体保存了 1 条记录.另一个持久化因违反主键约束而被数据库拒绝.

There is no data corruption actually. Because the first saveOrUpdate() does save 1 record for each entity as desired. The other persists are rejected by the database because of the primary key constraint violation.

我研究了乐观锁和悲观锁.我知道这些是在获取现有记录后才起作用的.这里的实体是新的,不存在的.

I researched about optimistic and pessimistic locking. I understood that these work after fetching an already existing record. Here the entities are new, not existing.

如何更好地解决这个问题?

How to approach this in a better way?

推荐答案

为什么异常是一个问题,你不能忽略它吗?如果您的数据库支持upsert"理论上,您可以通过在实体上添加以下注释来利用它:

Why is the exception an issue, can't you just ignore it? If your database supports "upsert" you could theoretically make use of that by adding the following annotation on your entity:

@org.hibernate.annotations.SQLInsert (sql = "INSERT INTO message_user (user_id) VALUES (?) ON CONFLICT DO NOTHING")

这篇关于使用 attachDirty (saveOrUpdate) 的休眠事务和并发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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