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

Questions:

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 ?

@Override
public ResponseEntity<?> delete(Long id) {
    return libelleRepository.findById(id).map(libelle -> {
        libelleRepository.delete(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.

Code:

@Autowired
    private UserService userService;

    @Transactional
    public String doFileOperation() {

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

        try {
            Files.write(Paths.get(testFile.getPath()),
                    lines,
                    StandardCharsets.UTF_8,
                    StandardOpenOption.CREATE,
                    StandardOpenOption.APPEND);
        } catch (IOException e) {
            e.printStackTrace();
        }


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

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

    @Override
    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.