Modification d'un id : création d'une nouvelle ligne au lieu de update.
Bonsoir,
Je suis sur un projet sur Spring Boot 2, et j'ai un souci au niveau de mon UserEntity :
L'affichage de tout les Users fonctionne, la création et la suppression d'un User également. Cependant, au niveau de la modification d'un User j'ai un problème lors de l'update.
Quand je modifie le firstname, lastname, admin et password tout fonctionne parfaitement, mais dés lors que je modifie le login qui est l'Id de mon UserEntity, Spring Boot créé une nouvelle ligne dans la table "user" de ma base de données au lieu d'update la ligne existante.
Çà fait quelques jours que je cherche une solution. J'ai également rechercher sur internet mais en vain.
Par contre, durant ma formation professionnelle en Java EE, je n'avais pas ce problème lors d'un update d'un Id.
Pouvez-vous m'aider s'il-vous-plait ? Merci par avance.
Cordialement.
Mon entity UserEntity :
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| @Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "user")
public class UserEntity {
@Id
@Column(name = "login", length = 30)
@NotNull
@Size(min = 7, max = 30)
private String login;
@Column(name = "firstname", length = 30)
@NotNull
@NotBlank
@Size(min = 3, max = 30)
@Pattern(regexp = "[a-z- ]{2,100}",
flags = Pattern.Flag.CASE_INSENSITIVE,
message = "Min : 3, Max : 30, caractères autorisés : a jusque z, un espace, un tiret(-)")
private String firstname;
@Column(name = "lastname", length = 30)
@NotNull
@NotBlank
@Size(min = 3, max = 30)
private String lastname;
@Column(name = "admin")
private Boolean admin;
@Column(name = "password", length = 30)
@NotNull
@NotBlank
@Size(min = 7, max = 30)
private String pwd;
@ManyToMany
private Collection<VideoEntity> videos = new ArrayList<>();
} |
Le formulaire pour éditer un User :
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
| <h1 class="text-center">Edit User</h1>
<form th:action="@{/admin/users/edit}" th:method="post" th:object="${user}" xmlns:th="http://www.thymeleaf.org">
<div class="form-group row justify-content-center">
<label for="firstname" class="col-md-1 col-form-label">Firstname</label>
<div class="col-md-4">
<input th:field="*{firstname}" type="text" class="form-control" id="firstname" placeholder="Enter firstname" aria-describedby="firstnameHelpInline">
<small id="firstnameHelpInline" class="text-muted">Must be 3-30 characters long.</small>
<div class="alert alert-warning" role="alert" th:if="${#fields.hasErrors('firstname')}" th:errors="*{firstname}"></div>
</div>
</div>
<div class="form-group row justify-content-center">
<label for="lastname" class="col-md-1 col-form-label">Lastname</label>
<div class="col-md-4">
<input th:field="*{lastname}"type="text" class="form-control" id="lastname" placeholder="Enter lastname" aria-describedby="lastnameHelpInline">
<small id="lastnameHelpInline" class="text-muted">Must be 3-30 characters long.</small>
<div class="alert alert-warning" role="alert" th:if="${#fields.hasErrors('lastname')}" th:errors="*{lastname}"></div>
</div>
</div>
<div class="form-group row justify-content-center">
<label for="login" class="col-md-1 col-form-label">Login</label>
<div class="col-md-4">
<input th:field="*{login}" type="text" class="form-control" id="login" placeholder="Enter login" aria-describedby="loginHelpInline">
<small id="loginHelpInline" class="text-muted">Must be 7-30 characters long, contain letters and numbers, and must not contain spaces, special characters, or emoji.</small>
<div class="alert alert-warning" role="alert" th:if="${#fields.hasErrors('login')}" th:errors="*{login}"></div>
</div>
</div>
<div class="form-group row justify-content-center">
<label for="pwd" class="col-md-1 col-form-label">Password</label>
<div class="col-md-4">
<input th:field="*{pwd}" type="text" class="form-control" id="pwd" placeholder="Enter password" aria-describedby="passwordHelpInline">
<small id="passwordHelpInline" class="text-muted">Must be 7-30 characters long, contain letters and numbers, and must not contain spaces, special characters, or emoji.</small>
<div class="alert alert-warning" role="alert" th:if="${#fields.hasErrors('pwd')}" th:errors="*{pwd}"></div>
</div>
</div>
<div class="form-group form-check">
<div class="col-md-12 text-center">
<input th:field="*{admin}" type="checkbox" class="form-check-input" id="admin">
<label class="form-check-label" for="admin">Admin</label>
</div>
</div>
<div class="col-md-12 text-center">
<button type="submit" class="btn btn-danger">Edit</button>
</div>
</form> |
Une partie du code de mon UserController concernant l'update d'un User :
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| @GetMapping(value= "/admin/users/edit")
public String editUser(@RequestParam("login") String login, Model model) {
if (login != null) {
Optional<UserEntity> user = userService.findById(login);
if (user.isPresent()) {
model.addAttribute("user", user.get());
model.addAttribute("body", "fragments/admin/user/edit");
return "index_admin.html";
} else {
return "redirect:/admin/users";
}
} else {
return "redirect:/admin/users";
}
}
@PostMapping(value = "/admin/users/edit")
public String editUserPost(@Valid @ModelAttribute("user") UserEntity userEntity, @RequestParam("login") String login,
BindingResult userBinding, Model model) {
if (userBinding.hasErrors()) {
model.addAttribute("userError", userBinding);
model.addAttribute("user", userEntity);
model.addAttribute("body", "fragments/admin/user/edit");
return "index_admin.html";
} else {
userService.saveOrUpdate(userEntity);
model.addAttribute("message",
"The user is edited !");
return "redirect:/admin/users";
}
} |
Et enfin l'UserService :
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| @Service
public class UserService {
@Autowired
private UserRepository userRepository;
public UserEntity saveOrUpdate(UserEntity user) {
return userRepository.save(user);
}
public void delete(UserEntity user) {
userRepository.delete(user);
}
public void deleteById(String login) {
userRepository.deleteById(login);
}
public Optional<UserEntity> findById(String login) {
return userRepository.findById(login);
}
public Iterable<UserEntity> findAll() {
return userRepository.findAll();
}
} |