As per java docs for @Lock annotations:
Annotation used to specify the LockModeType to be used when executing the query. It will be evaluated when using Query on a query method or if you derive the query from the method name.
As mentioned above it will be evaluated with @Query annotation or findBySomething..() method.
But as per my finding, when i put @Lock annotation with @Transactional in any method, and get record from db in that transaction method it is acquiring lock on db rows, ideally it should not(correct me if i am wrong):
I verified this with two transactions T1 and T2 as follows:
Starts T1 first, and fetch some records from db and sleep that thread and did not update them.
Now start T2 on other method having same @Lock with pessimistic write and @Transactional annotation and fetch same records and trying to update them, But when it is trying to commit those changes it waits for some time and then throw exception saying PessimsticLock timeout exception
@Transactional
@Lock(LockModeType.PESSIMISTIC_WRITE)
public boolean addInventory(Integer id){
repo.findById(id)// #statement 1
}
also when #statement 1 is called it does not fire "select for update" query instead only fire select query.
Is it true that @Lock can be used with @Transactional and all rows which are fetched under this transaction get lock ?
Using SpringBoot version 2.1.4.RELEASE