How to solve this concurrency saveing problem?
Hello!I got an issue on my desk to solve.
We got an system that saves records in a database with an EJB (stateless SessionBean) that uses Hibernate.
Each record describes a Part with a name. The table, "parts", looks like:
db_id, name, version, desc (where db_id is the primary_key)
Beside the unique db_id, the name and version "should" be unique, but there is no constraints in the db for this.
The architect of the system would like to minimize database constraints. The reason for this is not have business logic in the database.
Several clients can connect to the system. These clients can save Parts in the database.
The user enters the name and desc. If there is no Part with this name, then the Part will be saved with version = 1;
If the name exists then the Part will be saved with version = 2..and so on.
The problem is that two clients can save the same Part (same name) for the first time at the same time. The situation in the database will then be:
db_id, name, version, desc
1 , a , 1 , "A Part"
2 , a , 1 , "A Part"
The logic is
ejb.transaction type = "RequiresNew"
...
savePart("a", "A Part")
b = checkIfExist("a")
if(b)
session.save("a", "A Part", getNextVersion("a"))
else
session.save("a", "A Part", 1)
The problem seems to be that several clients can call this method simultaneous and if they are executed with same params, for a not existing Part, at the same time the method checkIfExist will return false for all calls and we get the same data in several records.
I hope that I have illustrated the problem well enough.
All comments how to solve this is most welcome and appreciated!
Best regards
Fredrik
Btw
We use Weblogic 8.1.5 for ejb container and Oracle 10g as database.