使用jpa和manytomany删除

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

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

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

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

@Override
    public void deleteUser(long id) {
        User u = userRepository.findById(id).get();
        Set<Role> roles = u.getRoles();
        while(roles.iterator().hasNext()) 
        {   
            Role role = roles.iterator().next();
            Set<User> users = role.getUsers();
            users.remove(u);
            role.setUsers(users);
            roleRepository.save(role);
            roles.remove(role);
        }
        u.setRoles(roles);
        userRepository.save(u);
        userRepository.deleteById(id);
    }

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

@Controller("error")
public class ErrorController {

    @ExceptionHandler(Exception.class)
    public ModelAndView handleException(HttpServletRequest request, Exception ex) {
        ModelAndView mv = new ModelAndView();

        mv.addObject("exception", ex.getLocalizedMessage());
        mv.addObject("url", request.getRequestURL());

        mv.setViewName("error");
        return mv;
    }

}

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

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 {

@Id
@Column(name = "user_id")
private Long userId;// primary key

@OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true)
private Set<Role> roles;

}

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

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

}

相关问题