Java: functional programming trap

A code that makes no sense!!

Sadly, fixing the two paradigmes of OOP and FP in Java gives really akward results, that can be seen below:

@Transactional(readOnly = false)
    public Try createAccount(String userId) {
        return
            userService.getUser(userId)
                .flatMapTry(
                    accountUser -> Try.of(() -> {
                        Account account = new Account(UUID.randomUUID().toString(), 0);

                        return accountRepository.save(account);
                    })
                );
    }

This code runs, but having a @Transactional annotation with type Try at the same time leads to a bug. The code will never rollback in case of a failure, due to the fact that all failures are hidden in the Try type.

This time one of my favourite types Try just does not do the job…

Advertisements