Home » Java » java – spring boot execution of two dependent methods-Exceptionshub

java – spring boot execution of two dependent methods-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment


I am developping an application using spring boot as framework. I have 2 methods the first one is deleting data from the database and the other one is deleting folder from the disk, so if i delete from the database and i can’t delete from the disc all the operation will fail. So how can i do that with springboot ?

public ResponseEntity<?> delete(Long id) {
    return libelleRepository.findById(id).map(libelle -> {
        return ResponseEntity.ok().build();
    }).orElseThrow(() -> new GeneralResourceNotFoundException("Libelle not found with id " + id));

How to&Answers:

You can use the Spring’s @Transactional for doing this.

Here is the sample code what I have tried. It performs a Database operation followed by a file operation in my example I’m trying to create a file. First am creating the file before performing the database operation and used TransactionSynchronizationAdapter to make sure the transaction is complete before commiting.


    private UserService userService;

    public String doFileOperation() {

        File testFile = new File("C:\test.txt");
        TxnListener transactionListener = new TxnListener(testFile);
        // DB Operation
        // File Operation
        List<String> lines = Arrays.asList("1st line", "2nd line");

        try {
        } catch (IOException e) {

        return "";
public class TxnListener extends TransactionSynchronizationAdapter {
    private File outputFile;

    public TxnListener(File outputFile) {
        this.outputFile = outputFile;

    public void afterCompletion(int status) {
        if (STATUS_COMMITTED != status) {
            if (outputFile.exists()) {
                if (!outputFile.delete()) {
                    System.out.println("Could not delete File" + outputFile.getPath() + " after failed transaction");

In case of exception during the Database operation afterCompletion will be called and the file will be deleted.

This way you can maintain the atomicity of the operation.