1
我想設計一個CRUD控制器,在這裏插入和刪除操作完美,但更新不起作用。提交更新時,只更新用戶表,但不更新角色表。更新不工作在休眠多對多關係表
User.java
@Entity
@Table(name="users")
public class User implements UserDetails {
@Id
@GeneratedValue (strategy = GenerationType.AUTO)
private Long id;
@Column(length = 128, nullable = false)
private String firstName;
@Column(length = 128, unique = true, nullable = false)
private String email; // required; unique
@Column(unique = true, nullable = false, length=128)
private String name;
@Column(length = 128, nullable = false)
private String password; // required
@Column
private boolean enabled;
@JsonBackReference
@ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinTable(
name = "company_user",
joinColumns = @JoinColumn(name = "userId"),
inverseJoinColumns = @JoinColumn(name = "companyId")
)
private Set<Company> companies = new HashSet<Company>();
@ManyToMany(fetch = FetchType.EAGER, cascade = {CascadeType.MERGE})
@JoinTable(
name = "user_role",
joinColumns = @JoinColumn(name = "userId", referencedColumnName="id"),
inverseJoinColumns = @JoinColumn(name = "roleId", referencedColumnName="id")
)
private Set<Role> roles = new HashSet<Role>();
Role.java
@Entity
public class Role extends BaseObject {
@Column(length = 64)
private String description;
UserController.java
@PostMapping("/saveUser")
public void save(@ModelAttribute User user, BindingResult bindingResult, HttpServletRequest req, HttpServletResponse rsp) throws IOException {
user.setPassword(new BCryptPasswordEncoder().encode(user.getPassword()));
// LOGGER.info("--------------role User ID----------" + user.getRoles());
user.setRoles(user.getRoles());
userService.registerUser(user);
req.setAttribute("users", userService.findAllUsers());
req.setAttribute("mode", "USER_VIEW");
rsp.sendRedirect("showUser");
}
**UserService.Java**
public User registerUser(User user) {
Optional<User> exists = userRepository.findOneByName(user.getName());
return exists.isPresent() ? userRepository.save(exists.get().merge(user))
: userRepository.save(user);
}
我怎樣才能overcom這種情況?請幫我.....
我真的不明白'user.setRoles(user.getRoles());';它不會向用戶實體添加任何「新」 –