I am facing a problem when two user are simultaneously trying to insert a record in a table and both of them getting the same id. I am generating the id (pattern xxx-xxx) in my DAO layer and the way I am doing this is - first I am retrieving the last id created and incrementing it by one to generate a new id and then inserting the records in the database with that new id and calling a commit.
How should I then handle this situation so that no two user end up having the same id.
Thanks
Ulf Dittmer
Marshal
Joined: Mar 22, 2005
Posts: 35237
7
posted
0
Most databases allow the key to be generated by the DB (using an auto-increment sequence); that will ensure that they are unique.
If the ID needs to be generated in the application code, then that code needs to be made thread-safe (maybe by synchronizing it).
thanks for the reply Ulf.
Unfortunately I cannot use the database incremantor due the requirements, which are forcing me to handle the incrementing logic in application code. This ID is sort of a ticketID.
The only worry I have with respect to using the synchronization is - how much will it impact the performance of the application as I am inserting records in more than 10 tables after generating the ID.
Ulf Dittmer
Marshal
Joined: Mar 22, 2005
Posts: 35237
7
posted
0
In that case, only the code that increments the ID needs to be synchronized, not the full DB logic that subsequently makes use of that ID, right? (I'm assuming that it's not important to re-use an ID in case of a DB rollback.)