Francesco Galgani
Francesco Galgani

Reputation: 6249

Spring Boot: check if a given String is unique in the database

In Spring Boot, I need to check if a random String is unique. I suppose that a good way is to use an Entity with an unique column, and than:

if the String exists in the repository, adds it to the repository and return it.

That involses some code that may fail in a multithread environment, because while a thread is checking if a given String exists in the database, another thread can add it to the database at the same time.

Could you give me some hits to solve this problem? Thank you.

Upvotes: 0

Views: 426

Answers (2)

DIMAKATSO BOPAPE
DIMAKATSO BOPAPE

Reputation: 153

You can enable transaction locks on query Methods with @Lock annotation.

@Lock(LockModeType.PESSIMISTIC_READ)
public Optional<Person> findById(Long PersonId);

Upvotes: 1

Chris
Chris

Reputation: 5663

You can use pessimistic locking to solve that.

Spring has a @lock annotation with a lock type pessimistic, that might serve your needs. Otherwise you can implement your application in a way where it locks the entity before querying and releases the lock afterwards.

I would start from here: https://en.wikipedia.org/wiki/Record_locking

Upvotes: 1

Related Questions