Search code examples
javaspringspring-bootspring-data-jpaspring-data

Spring transaction doesn't rollback after Exception


I'm creating new user and after that when I create profile for user by createProfileRequest() and service retrive me an error, user is not being rolled back

@Transactional(rollbackFor = {RestClientException.class, IllegalStateException.class})
    public User createUser(UserRegistrationForm registrationForm) throws UserAlreadyExistsException {
        if (userRepository.existsUserByEmailOrUsername(registrationForm.getEmail(), registrationForm.getUsername()))
            throw new UserAlreadyExistsException("User with credentials "  +
                    registrationForm.getEmail() + "/" + registrationForm.getUsername() + " already exists");

        User user = new User(registrationForm.getUsername(), registrationForm.getEmail());
        user.setPassword(passwordEncoder.encode(registrationForm.getPassword()));
        user.setRoles(getDefaultRoles());

        userRepository.save(user);

        createProfileRequest(user);

        tokenService.createToken(user.getId(), TokenType.ACTIVATION);
        log.info("Created user with id: " + user.getId());
        return user;
    }

    private void createProfileRequest(User user) throws RestClientException, IllegalStateException {
        ObjectNode profile = new ObjectMapper().createObjectNode();
        profile.put("userId", user.getId());
        profile.put("visibleName", user.getUsername());
        restTemplate.postForLocation("http://profile/api", profile);
    }

Solution

  • I think your problem is with the createProfileRequest() method visibility here. Transactional annotation works by default only with public methods.