Sorry this is such a long question but it touches on a general issue with databases:
I’m using sqlite/jdbc (in this case), and I’m trying to keep track of the automatic ID’s created when I add rows to a table. The database has a main table ‘Person’ and other tables called ‘training’ and ‘induction’. The idea is that the persons name and other basic details go into the ‘Person’ table, and that one person many have many ‘trainings’ and ‘inductions’. So, I can look up all the inductions for a given person by SELECT * FROM INDUCTIONS WHERE PERSON_ID = whatever.
The problem is in creating the database, I have to add a person, then keep track of the AUTOINCREMENTing ID they got and then create the entries in the other table with that ID as a foreign key:
So
int id = 0;
PreparedStatement prepPerson = conn.prepareStatement("insert into persons values (?, ?);");
prepPerson.setString(2, p.getName());
prepPerson.addBatch();
Then
PreparedStatement prepInductions = conn.prepareStatement("insert into inductions values (?, ?, ?, ?);");
Then loop over all the inductions {
prepInductions.setInt(2, id);
prepInductions.setString(3, i.getSite());
prepInductions.setString(4, i.getExpiryDate());
prepInductions.addBatch();
}
I want the interactions with the data base to be ‘atomic’, so I want to do
prepPerson.executeBatch();
prepInductions.executeBatch();
id++;
I realise could instead add the person, do getGeneratedKeys() and then add the inductions with the correct row_id of the new person, but I don’t want an exception to occur after the Person is added but before the Inductions are. If that happens then I’ll have to roll back time and remove the person.
At the moment as I know I’m creating the database afresh everytime from an external source I’m keeping track of the row_id with a local integer variable, and I know that’s living dangerously.
Isn’t there a general solution to this sort of situation? Or am I worrying much about the ‘atomic’ interactions with the database?
Do use
getGeneratedKeys()to retrieve the generated ID.To keep data integrity, use transactions. Normally, JDBC uses ‘autoCommit’ mode, but in this case you’ll need to handle the transaction manually.
Call
.setAutoCommit(false)on your connection and use.commit()and.rollback()to commit or discard changes.(Check the Connection Javadoc).