使用jpa和manytomany删除

kxe2p93d  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(335)

我按照这个教程设置了一个springboot项目,其中包含一个带有jpa和springsecurity的登录/注册系统。在教程代码中,它生成一个“users”、“roles”和“users\u roles”表。现在我想向控制器添加一个路由,通过将此路由添加到控制器,可以按id删除用户:

  1. @RequestMapping(value = "/user_delete", method = RequestMethod.GET)
  2. public String deleteUser(@RequestParam long id) {
  3. userService.deleteUser(id);
  4. return "redirect:/admin/users";
  5. }

并向userservice添加了一个delete方法,如下所示:

  1. @Override
  2. public void deleteUser(long id) {
  3. User u = userRepository.findById(id).get();
  4. Set<Role> roles = u.getRoles();
  5. while(roles.iterator().hasNext())
  6. {
  7. Role role = roles.iterator().next();
  8. Set<User> users = role.getUsers();
  9. users.remove(u);
  10. role.setUsers(users);
  11. roleRepository.save(role);
  12. roles.remove(role);
  13. }
  14. u.setRoles(roles);
  15. userRepository.save(u);
  16. userRepository.deleteById(id);
  17. }

我还添加了一个简单的错误控制器,如下所示:

  1. @Controller("error")
  2. public class ErrorController {
  3. @ExceptionHandler(Exception.class)
  4. public ModelAndView handleException(HttpServletRequest request, Exception ex) {
  5. ModelAndView mv = new ModelAndView();
  6. mv.addObject("exception", ex.getLocalizedMessage());
  7. mv.addObject("url", request.getRequestURL());
  8. mv.setViewName("error");
  9. return mv;
  10. }
  11. }

现在,每当我调用delete路由时,它都会转到我的错误页,而控制台中没有真正的消息。我试着添加 cascade = CascadeType.ALL 或删除,但都不起作用,仅当启动应用程序时,我会收到此异常消息(应用程序仍会启动):

  1. Error executing DDL "alter table users_roles add constraint FK2o0jvgh89lemvvo17cbqvdxaa foreign key (user_id) references users (id)" via JDBC Statement

如何修改教程中的代码以删除用户?

atmip9wb

atmip9wb1#

我假设你有一个实体 bidirectional 关系如下所示。
你需要添加 cascade = CascadeType.ALL 以及 orphanRemoval = true ,你也可以试试 cascade = CascadeType.REMOVE ```
@Entity
public class User implements java.io.Serializable {

  1. @Id
  2. @Column(name = "user_id")
  3. private Long userId;// primary key
  4. @OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true)
  5. private Set<Role> roles;

}

@Entity
public class Role implements java.io.Serializable {

  1. @ManyToOne(fetch = FetchType.LAZY)
  2. @JoinColumn(name = "user_id")
  3. private User user;

}

展开查看全部

相关问题