vzhemevko
vzhemevko

Reputation: 905

Upsert in Spring Data

There is a table

columns: id(pk), name, attribute 
unique constraint on (name, attribute).

There are a bunch of threads which insert in the table if a record is not there. Spring Data is used for that and it's done it a transaction which could take some time. The records could be the same, meaning same (name, attribute), simultaneously in a couple of threads. From time to time race condition happens, thread A tries to commit a new record whereas thread b committed the same before thread A read it.

Are there any approaches on how to do upsert in this kind of situations?

Perhaps, there are other suggestions to resolve this issue, would be happy to hear them.

Upvotes: 3

Views: 4225

Answers (1)

Jens Schauder
Jens Schauder

Reputation: 81960

Either do it the JPA way:

Try to find the entity, if it is not there, save it. If it is there there is nothing to do, but of course you could update it by manipulating the found entity.

Alternatively go SQL and write an actual upsert/merge statement which many database dialects support.

Upvotes: 3

Related Questions