Reputation: 2917
I am developing a web-service that will be used by several clients. I am using EclipseLink as JPA provider. When calling a method in the web-service from a client, then I have observed that EclipseLink uses a thread in a thread pool to call the method which means the method can be called simultaneously at the same time from different threads in that thread pool.
In some of the methods I do some critical writes to some tables in the database and I need do implement some kind of locking mechanism. Is it a good practice to synchronize the methods when writing to database or do I need to lock the entire table in MySQL?
Some of the writes looks like this in pseudo code:
1. insert_into_TableA(getLastInsertedIdInTableA + 1);
2. insert_into_TableB(getLastInsertedIdInTableB + 1);
3. int id_A = getLastInsertedIdInTableA + 1;
4. int id_B = getLastInsertedIdInTableB + 1;
5. insert_into_TableAB(id_A, id_B);
Database structure below:
TableA TableAB TableB
pk tableA_id pk tableA_id pk tableB_id
pk tableB_id
My second question: I am not using autoincrement
in my tables, so is it a good practice, when inserting new rows, to get the ID of the last inserted row and then just increment it by 1 to insert the new row? Or can I use some good methods in EclipseLink to do this for me?
Upvotes: 0
Views: 2255
Reputation: 328800
What you need is a "transaction."
Usually, the container will make sure that a new transaction is started when a new request comes in and commits the transaction after the code to process the request completes (unless an exception is thrown).
The problem is getLastInsertedId
- this won't work. Different transactions might see the same value here. The solution is to let the database figure out a new, free ID for you.
Use an "identity column" instead. In MySQL, that would be NOT NULL AUTO_INCREMENT.
Upvotes: 1