I have a problem to control concurrency when inserting data through my web application.
Context: I have 3 tables (X, Y and Z) that record patient's hospitalizations. A patient cannot have more than one active hospitalization.
Currently my application do a verification before the hospitalization INSERT in the database, that checks if the patient is already hospitalized.
However, this verification does not work when two or more users try to admit the same patient at the same time.
What I do now:
1 - verify if patient is already hospitalized (SELECT in table X)
If not:
begin transaction A;
2 - INSERT in table X;
3 - INSERT in table Y;
4 - INSERT in table Z;
end transaction A;
As I mentioned before, the verification in 1 try to avoid patients from being hospitalized twice or more. However, it do not work if two (or more) users try to admit the same patient at the same time.
Maybe I can use something that may lock the SELECT statement from being executed until the transaction A be finished. In that way the SELECT would identify that the patient is already registered when executed.
I would like to treat this problem using EXPLICITING LOCKING from PostgreSQL in database. Accordingly to the documentation I can do something like that using the ACCESS EXCLUSIVE lock mode (since it is the only mode capable o lock an select statement).
But how to implement this ACCESS EXCLUSIVE lock in Hibernate?
I've already check and is not possible to treat this using constraints in database