使用@Transactional注释在类中进行实体更新

时间:2018-05-02 22:10:30

标签: java spring jpa spring-data

我有自己的UserDetails实现

public class CustomUserDetails extends org.springframework.security.core.userdetails.User {
     private UserEntity userEntity;
...
}

我的登录实现

@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {
...

@Override
public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException {
    Optional<UserEntity> userOptional;
    if(username.contains("@")) {
        userOptional = userRepository.findByEmailIgnoreCaseAndEnabledTrue(username);
    } else {
        userOptional = userRepository.findByUsernameIgnoreCaseAndEnabledTrue(username);
    }

    ...

    return new CustomUserDetails(userOptional.get().getUsername(),
                                 userOptional.get().getPassword(),
                                 grantedAuthorities,
                                 userOptional.get());
}

我使用服务获得实体

@Service("authorizationService")
public class AuthorizationServiceImpl implements AuthorizationService {

    @Override
    public UserEntity getUser() {
        return ((CustomUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUserEntity();
    }
}

并为标有@Transactional注释的网站分配新密码,但不会在数据库中更新

@Service("userPersistenceService")
@Transactional
public class UserPersistenceServiceImpl implements UserPersistenceService {
    /**
 * {@inheritDoc}
 */
@Override
public void updatePassword(
        @NotNull @Valid final ChangePasswordDTO changePasswordDTO
) throws ResourceNotFoundException, ResourceBadRequestException {
    log.info("Called with changePasswordDTO {}", changePasswordDTO);

    final UserEntity user = this.authorizationService.getUser();

    if(!EncryptUtils.matches(changePasswordDTO.getOldPassword(), user.getPassword())) {
        throw new ResourceBadRequestException("The entered password doesn't match the old password");
    }

    user.setPassword(EncryptUtils.encrypt(changePasswordDTO.getNewPassword()));
}
}

我希望在user.setPassword(...)期间立即自动更新数据库中实体的数据。这就是我添加@Transactional注释的原因。但它不起作用。为什么呢?

0 个答案:

没有答案