Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unique constraint violation error in while SaveOrUpdate

I have a hibernate entity called customer which contains the information about customer.In my method i m getting customer details as parametres which i need to insert in database. So to remove duplicate entries i m checking whether that customer already exists in db or not. But the problem is that if two calls are made to same method at one instant with same customer information then i m getting constraint violation error. I thought saveOrupdate() will solve the problem but it hasnt. Can someone suggest a solution for this scenario.

like image 779
Naman Avatar asked Feb 19 '23 18:02

Naman


2 Answers

saveOrUpdate is for completely different purpose. It is for persisting an entity which might already be persisted (having an id and all) or it might be a fresh id. It has nothing todo with concurrent access.

For your problem there are two options, known as optimistic locking and pessimistic locking.

Pessimistic Locking: You create a lock before checking if the customer exists, so only the current thread can continue, it does it's check and acts accordingly. Any other thread coming with the same data will have to wait until the update or insert of the first thread finished. The lock could be implemented in the database, using hibernate or simply a synchronized block if you run on a single machine.

Optimistic Locking: You just go ahead just as you do right now. But you put an exception handler in place for handling the collision case you described in the question.

Pessimistic Locking is probably easier to implement using a synchronized block but it will affect performance and scalability pretty bad.

like image 51
Jens Schauder Avatar answered Feb 27 '23 11:02

Jens Schauder


saveOrUpdate works on the primary key attriute value in the object e.g. if 0 is default for new objects, and your new customer object is having the primary key attributes set as 0 then it will always attempt to save(insert) and never attempt to update. It will attempt to update only when primary key attribute is non zero value. This is the reason saveOrUpdate is not solving your problem.

I am not sure what you can do better than handling unique constraint exception as work around.

like image 31
Yogendra Singh Avatar answered Feb 27 '23 13:02

Yogendra Singh