0

I have a situation where I need to pick one entry from a table [table containing only 1 column id which is also a primary key], and in the same transaction I want to increment the key value and save it in the database. During this transaction, I don't want any other transaction to read the table, since unique id is required every time. For e.g. table contains only one entry with id = 1 initially,

In transaction t1 -> select entry from table where id = 1 -> some processing -> save a new entry in the table [not incrementing id explicity since its AUTO_INCREMENT type].

Now during t1, no read should be made on this table [and I don't want to discard these read requests], read can be made only after 2nd entry with id=2 is stored in the table.

Findings: After some research I came to know about optimistic and pessimistic lock types and found pessimistic one more suitable, but still cannot relate to my situation. Please guide.

Adding code level changes that I have done to lock transaction:

public interface CodeKeyRepository extends JpaRepository<CodeKey, Integer> {

    @Lock(LockModeType.PESSIMISTIC_WRITE)
    @QueryHints({@QueryHint(name = "javax.persistence.lock.timeout", value = "3000")})
    CodeKey findFirstByOrderByIdDesc();
}

CodeKey is the entity for above mentioned table, containing only 1 column id.

  • Are you looking for locking on the application side, or in the database itself? Will there be more than one database client? – Tim Moore Aug 06 '21 at 06:20
  • @TimMoore Hi, I'm trying the locking at application side in Springboot framework using JPA. The table will be accessed from my application only, but it will have multiple instances deployed on different server [one instance on one server]. – Devender kumar Aug 06 '21 at 06:44
  • If you have multiple instances, then I don't think locking at the application side will do what you want. Each instance could enforce single threaded access, but you could have multiple instances accessing the database at the same time. – Tim Moore Aug 06 '21 at 06:47
  • @TimMoore I have added the code changes while calling database in the description, by which I'm trying to achieve 1 transaction at a time. And yes, synchronization won't work in case of multiple server., That's why I'm trying to lock the database call. – Devender kumar Aug 06 '21 at 07:00
  • Thanks for adding code. It looks like you're using Spring Data JPA, correct? Unfortunately, I don't know much about that library, but from a quick look at https://www.baeldung.com/java-jpa-transaction-locks, what you're doing looks correct. Is it not working? – Tim Moore Aug 06 '21 at 07:04
  • Thanks for your input @TimMoore , and yes what I'm doing is most probably right, but I'm not able to test that case [where 2 requests from 2 different servers hits the locking code at exactly same time] to be 100% sure. Thanks anyway. – Devender kumar Aug 11 '21 at 18:16

0 Answers0