Hibernate Transactions and Concurrency Using attachDirty (saveOrUpdate)

放肆的年华 提交于 2021-01-29 14:24:43

问题


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

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.

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

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?


回答1:


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")


来源:https://stackoverflow.com/questions/64754720/hibernate-transactions-and-concurrency-using-attachdirty-saveorupdate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!