SpringBoot应用程序 - 未使用Postgres DB提交AuditorAware事务

时间:2016-09-20 00:50:59

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

我正在尝试使用预先存在的数据加载Spring启动应用程序。我想用“system”用户填充数据。我有以下组件定义被拦截并创建一个“系统”用户。问题是这个组件事务在针对H2 运行spring boot应用程序时被提交到数据库但是在使用PostgreSQL数据源运行应用程序时它没有被提交。请帮我弄清楚如何提交交易?

getCurrentAuditor方法的重写实现如下

@Transactional
@Component("auditorProvider")
public class UserAuditorAware implements AuditorAware<User> {

    @Inject
    private UserRepository userRepository;

    private User _systemUser;

    @Override
    public User getCurrentAuditor() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null) {
            if (_systemUser != null) {
                return _systemUser;
            }
            Optional<User> systemUser = userRepository.findOneByUsername("system");
            if (!systemUser.isPresent()) {
                // TODO: decide on which user to designate when entities are created by devices
                User user = new User("system");
                user = userRepository.save(user);
                userRepository.flush();
                systemUser = Optional.of(user);
            }
            _systemUser = systemUser.get();
            return _systemUser;
        }
        CurrentUser userDetails = (CurrentUser) authentication.getPrincipal();
        return userDetails.getUser();
    }
}

主应用程序类有以下注释。

@ComponentScan
@EnableAutoConfiguration(exclude = { MetricFilterAutoConfiguration.class, MetricRepositoryAutoConfiguration.class, SecurityAutoConfiguration.class })
public class Application {
...

1 个答案:

答案 0 :(得分:0)

我必须要求RENEIRES_NEW传播值才能解决此问题。它创建新事务并在存在时暂停。不确定默认传播无效的原因。

@Transactional(propagation= Propagation.REQUIRES_NEW)
@Component("auditorProvider")
public class UserAuditorAware implements AuditorAware<User> {

    @Inject
    private UserRepository userRepository;

    private User _systemUser;

    @Override
    public User getCurrentAuditor() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null) {
            if (_systemUser != null) {
                return _systemUser;
            }
            Optional<User> systemUser = userRepository.findOneByUsername("system");
            if (!systemUser.isPresent()) {
                // TODO: decide on which user to designate when entities are created by devices
                User user = new User("system");
                user = userRepository.save(user);
                userRepository.flush();
                systemUser = Optional.of(user);
            }
            _systemUser = systemUser.get();
            return _systemUser;
        }
        CurrentUser userDetails = (CurrentUser) authentication.getPrincipal();
        return userDetails.getUser();
    }
}