【问题标题】:Spring transaction doesn't rolback after Exception异常后Spring事务不回滚
【发布时间】:2019-04-10 17:05:24
【问题描述】:

我正在创建新用户,之后当我通过 createProfileRequest() 为用户创建个人资料并且服务检索错误时,用户没有被回滚

@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);
    }

【问题讨论】:

  • 使用@TransactionSynchronizationManager
  • 您使用的是哪个数据库?能否提供对应TransactionManager的配置?
  • 我用的是mysql,没有配置TransactionManager。我使用 spring boot 进行自动配置
  • 错误是什么意思?抛出了什么异常?
  • RestClientException.class - 在服务器上处理数据时出错,IllegalStateException.class - 当没有注册服务时。这都是可能的。

标签: java spring spring-boot spring-data-jpa spring-data


【解决方案1】:

我认为您的问题在于此处的 createProfileRequest() 方法可见性。默认情况下,事务注解仅适用于公共方法。

【讨论】:

    猜你喜欢
    • 2018-08-09
    • 2022-07-22
    • 2016-08-14
    • 1970-01-01
    • 1970-01-01
    • 2019-06-22
    • 2015-10-03
    • 2015-03-02
    • 2016-11-03
    相关资源
    最近更新 更多