Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
802 views
in Technique[技术] by (71.8m points)

spring - Hibernate Transactions and Concurrency Using 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.

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?

Concurrent calls causing attachDirty saveOrUpdate() to always try to save

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...