Da49
Da49

Reputation: 117

How to prevent duplicate entries being created in database in quick succession? (JPA)

I have a project whereby users post JSON to my API, which is then deserialized to an entity and persisted to the database. Since running a load testing tool which posts many requests (using the same API key, but as different 'users') in quick succession, I have found that some of my entities are duplicating in the database.

Although my code checks if the object already exists in the database, some of the requests are firing too fast concurrently and they are bypassing the check.

Using an entity manager, I think each request is under its own transaction, but I'm not sure how to 'lock' these transactions. Is there any way to prevent this duplication outside of putting the creation code inside of a general java synchronization block?

Thanks.

Upvotes: 2

Views: 6075

Answers (2)

lorinpa
lorinpa

Reputation: 556

If you are using a relational database (I.E. SQL), then the easiest way is to have the database do it for you. You and a unique constraint to the database table:

CREATE UNIQUE INDEX unique_author_name ON authors (first_name, last_name);

The above example has database table called "authors". Each author has a first and last name. The constraint prevents the database from storing 2 "Mark Twain"'s.

JPA will throw a PersistenceException and ConstraintViolationException when an attempt to add a duplicate is encountered.

Hope that helps :)

Upvotes: 2

Balázs Németh
Balázs Németh

Reputation: 6637

First you can create unique constraints on the table, and if there is a try to insert a duplication, an exception will be thrown.

An other thing is to change your transaction isolation level to a more strict one (serializable?). But there is a trade-off because it will slow down your access to the DB.

I recommend using the first approach, especially because these conflicts won't occur to often, except in your load tests.

Upvotes: 0

Related Questions