-1

当我转到 /confirmation-account 链接时,在 tomcat 控制台中我可以看到 if 和 else 块也被执行。我可以看到:

从 ColorConsoleHelper.getGreenLog("loginView") 和 ColorConsoleHelper.getGreenLog("confirmationAccountView") 打印

这真是奇怪的行为。为什么?

 @RequestMapping(value = "/confirmation-account", method = RequestMethod.GET)
 @Transactional
 public ModelAndView displayConfirmationAccountPage(ModelAndView modelAndView,  @RequestParam Map<String, String> requestParams) {

    final int ACTIVE_USER   = 1;

    // find the user associated with the confirmation token
    UserEntity userEntity = userService.findUserByConfirmationToken(requestParams.get("token"));

    // this should always be non-null but we check just in case
    if (userEntity!=null) {

        // set the confirmation token to null so it cannot be used again
        userEntity.setConfirmationToken(null);

        // set enabled user
        userEntity.setEnabled(ACTIVE_USER);

        // save data: (token to null and active user)
        saveAll(userEntity.getTrainings());

        /*
            RedirectAttributes won't work with ModelAndView but returning a string from the redirecting handler method works.
         */

        modelAndView.addObject("successMessage", "Konto zostało pomyślnie aktywowane!");
        modelAndView.setViewName("loginView");
        ColorConsoleHelper.getGreenLog("loginView");

    } else {

        ColorConsoleHelper.getGreenLog("confirmationAccountView");
        modelAndView.addObject("errorMessage", "Link jest nieprawidłowy...");
        modelAndView.setViewName("confirmationAccountView");
    }

    return modelAndView;
}


public void saveAll(List<TrainingUserEntity> trainingUserEntityList) {
    for ( TrainingUserEntity trainingUserEntity : trainingUserEntityList) {
        entityManagerService.mergeUsingPersistenceUnitB(trainingUserEntity);
    }
}

public void mergeUsingPersistenceUnitB(Object object) {
     EntityManager entityManager = getEntityManagerPersistenceUnitB();
     EntityTransaction tx        = null;
     try {
         tx = entityManager.getTransaction();
         tx.begin();
         entityManager.merge(object);
         tx.commit();
     } 
     catch (RuntimeException e) {
         if ( tx != null && tx.isActive() ) tx.rollback();
         throw e; // or display error message
     }
     finally {
         entityManager.close();
     }
 }
4

1 回答 1

0

以下解决方案和解释:

因为/confirmation-account链接被调用了两次,是动态代理和controller中注解的@Transactional方法引起的 必须检查调用了多少displayConfirmationAccountPage方法。这是解决方法。

您认为注释@Transactional 控制器方法好还是不好?

于 2018-03-30T18:18:57.207 回答