JPA multithreaded Add if Not Exist?
java, jpa
Solution
Yes, this whole operation should be executed inside a transaction, such as provided by JTA or Spring's `@Transactional`. If the transaction is isolated at the proper level (I think `REPEATABLE_READ` for this case), the underlying persistence system will ensure that colliding writes don't occur, either by blocking one transaction until the other is complete (essentially what `synchronized` does in Java), or by stopping and rolling back the second transaction when it detects the conflict (which you can then retry).
Problem
I have a server function which is called by many clients, many times exactly at the same time. The server function does the following: - get param1 from client - creat object x (new objectx(param1)) - check if object x exists in db (jpa select query) - if not exists add object x (jpa store entity) - add y (jpa store entity) This goes wrong when two or more clients run the function at the same time, multiple x objects get added to the database. I simply solved this by creating a singleton manager class with a synchronized method which does the above. Works nicely, cause now the function can only be called by one client at a time. (but i do get a problem when there are 2 servers, but that isn't the case yet) But i was wondering is there a better way to solve this problem with jpa?