首页 > 解决方案 > 检查重复的用户名阻止更新用户

问题描述

我有以下用于添加用户的 Java 控制器:

@GetMapping("/registration")
public String registration(Model model) {
    if (securityService.isAuthenticated()) {
        return "redirect:/";
    }

    model.addAttribute("userForm", new User());

    return "registration";
}

我还有以下验证器来防止重复的用户名:

if (userService.findByEmail(user.getEmail()) != null) {
    errors.rejectValue("username", "Duplicate.userForm.username");
}

我现在正在尝试添加一个控制器来更新现有用户。我创建了以下内容以使用与创建用户时相同的注册表单:

@GetMapping("/users/showFormForUpdate")
public String showFormForUpdate(@RequestParam("userId") long theId, Model theModel) {
        
    User theUser = userService.findById(theId);
        
    theModel.addAttribute("userForm", theUser);
        
    return "registration";
}

我的问题是,当我尝试更新我的重复用户时,如果我不更改用户名,就会出现警报。

这是我在注册表单中发出警报的代码:

<div class="form-group">
    <input type="text" th:field="*{username}" class="form-control" placeholder="Username"
                       autofocus="true">
    <span style="color:red" class="has-error" th:if="${#fields.hasErrors('username')}" th:errors="*{username}"></span>
</div>

总之,当我创建用户时,我希望标记任何重复的用户名,但如果我正在更新用户,我不希望这样。我如何更新我的用户但保持防止重复用户的能力?我正在使用addAttribute. org.springframework.ui.Model我知道一种选择是使用不同的形式进行更新,但我希望应该有一种方法可以同时使用一种形式。

标签: javaspring-bootspring-data-jpathymeleaf

解决方案


if (userService.findByEmail(user.getEmail()) != null) {
  errors.rejectValue("username", "Duplicate.userForm.username"); }

避免上面的代码级别验证,如果用户名重复,让数据库抱怨。即在注册过程中,因为该User对象没有userId,JPA 有一个insert,如果存在重复,您将收到一个 通知DataIntegrityViolationException。在更新期间,JPA 会执行一个,update因为userId存在 ,并且不会导致DataIntegrityViolationException.


推荐阅读