0

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.

Francesco Galgani
  • 6,137
  • 3
  • 20
  • 23
  • 1
    There is too much here to answer in one question: what type of database are you using SQL/NoSQL? which flavor?; how are you accessing the database spring-data, Hibernate, etc? Having a succinct minimal reproducible answer would also help https://stackoverflow.com/help/minimal-reproducible-example – Nick Tomlin May 22 '20 at 17:25
  • You're right: my question is very generic. However the two answers were both useful to me because I didn't know anything about locking. I wrote a new question more specific, with a succinct minimal code: https://stackoverflow.com/questions/61969707/spring-boot-locking-code-to-get-an-unique-id – Francesco Galgani May 23 '20 at 09:08

2 Answers2

1

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

Chris
  • 5,109
  • 3
  • 19
  • 40
1

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

@Lock(LockModeType.PESSIMISTIC_READ)
public Optional<Person> findById(Long PersonId);
DIMAKATSO BOPAPE
  • 153
  • 1
  • 2
  • 11