Reverting changes on objects after a database rollback
posted 5 years ago
I have one specific object that is persisted in two tables of the database. The database contains internationalized data, so one table, say TABLE_X, keeps the non-internationalized data (references to other tables, and some numbers), and the other, say TABLE_X_DETAILS keeps the internationalized (mainly descriptions in different languages).
I have a java class, say CLASS_X, which must be persisted. When I persist some instance of CLASS_X, I must perform 2 inserts: one on TABLE_X, and other insert on TABLE_X_DETAILS. TABLE_X has a generated primary key. I have a DAO class that performs the task.
Before the database inserts, the instance of CLASS_X have a null id. When the insert on TABLE_X is performed, I get the generated primary key, then I use it to insert the localized details on TABLE_X_DETAILS, and if all goes well, I set the generated id on the object.
My insert method looks like this:
The issue here is that the insert method may called as part of bigger transactions that performs many other changes. If one of those transactions fails, I need to remove the generated id on the objects. Is there a way to identify that a transaction was rolled back and clean up the changes I performed on the objects? I was looking for some kind of transaction listener, but found nothing that could help me here. I would like to have something like the below (I invented below example just to make my point):
Is there anything I can use to implement that bevahiour? I'm using spring JDBCTemplate but could not find anything related.
Thanks and regards,