Nested @Transactional methods with @Async

后端 未结 2 1129
一个人的身影
一个人的身影 2021-02-07 13:44

I\'m using Spring with JPA. I have @EnableAsync and @EnableTransactionManagement turned on. In my user registration service method, I have a few other

2条回答
  •  猫巷女王i
    2021-02-07 13:59

    Make a try by creating a new UserService class to manage user check, like so

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public User createOrUpdateUser(User newUser) {
        String username = newUser.getUsername();
        String email = newUser.getEmail();
    
        // ... Verify the user doesn't already exist
    
        // I have tried all manner of flushing and committing right here, nothing works
        newUser = userDAO.merge(newUser);
        return newUser;
    }
    

    then in the actual class, change

    private User registerUser(User newUser, Boolean waitForAccount) {
        String username = newUser.getUsername();
        String email = newUser.getEmail();
    
        // ... Verify the user doesn't already exist
    
        // I have tried all manner of flushing and committing right here, nothing works
        newUser = userDAO.merge(newUser);
    

    by

    private User registerUser(User newUser, Boolean waitForAccount) {
        newUser = userService.createOrUpdateUser(newUser);
    

    The new userService with @Transactional REQUIRES_NEW should force the commit and solve the issue.

提交回复
热议问题