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

查看:52
本文介绍了使用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天全站免登陆