I have simple code where I am adding into the tables and if one of the table entry fails to add the data into the table then delete the data from all the table.
Code :
@Component
public class Operation {
...
public void execute(Long seqNumber) {
try {
addTable1(seqNumber);
addTable2(seqNumber);
addTable3(seqNumber);
}
} catch(Exception e) {
deleteAllRecords(seqNumber);
}
}
private void addTable1(Long seqNumber) throws Exception {
Table1 data = new Table1();
...
table1Repository.save(data);
}
private void addTable2(Long seqNumber) throws Exception {
Table1 data = new Table1();
...
table2Repository.save(data);
}
private void addTable3(Long seqNumber) throws Exception {
Table1 data = new Table1();
...
table3Repository.save(data);
}
private void deleteAllRecords(Long sequenceNumber) {
table1Repository.deleteBySequenceNumber(sequenceNumber);
table2Repository.deleteBySeqNum(sequenceNumber);
table3Repository.deleteBySeqNum(sequenceNumber);
}
...
}
So here, if the system fails to add the data into table3 then data from table1 and table2 also should be removed.
However, I get the following error when the code goes to catch block and call deleteAllRecords(...)
:
org.springframework.dao.InvalidDataAccessApiUsageException: No EntityManager with actual transaction available for current thread - cannot reliably process 'remove' call; nested exception is javax.persistence.TransactionRequiredException: No EntityManager with actual transaction available for current thread - cannot reliably process 'remove' call
Questions :
Am I doing anything wrong?
How can I revert/delete the changes from different tables when I get an exception?
Any help would be appreciated.