Like i said in title i need to run another query in case of an exception is thrown by the main query. Here is an example pl/sql to understand better what i'm talking about:
BEGIN NULL;
--Some insert operations
INSERT INTO TEST (VALUE, ID) SELECT 'abc', 1 FROM DUAL;
INSERT INTO TEST (VALUE, ID) SELECT 'abc', 2 FROM DUAL;
INSERT INTO TEST (VALUE, ID) SELECT 'abc', 3 FROM DUAL;
COMMIT;
EXCEPTION
WHEN OTHERS THEN
ROLLBACK;
DELETE TEST WHERE ID = 5; --If something goes wrong with the insertions above they are rolled back and this delete operation executed
COMMIT;
RAISE;
END;
How can i achive this kind of query with spring boot?
Here is what i have in mind:
@Transactional
public void sqlOperation() {
try {
someRepository.saveAll(someList);
} catch (Exception e) {
// programmatic transaction management
TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);
transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
transactionTemplate.execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(TransactionStatus status) {
someRepository.deleteById(someId);
}
});
throw new someException(e);
}
}
but this is messy and in my case not good enough(i need to run other queries etc.). So what is my alternatives, what is the elegant way of doing this?