Alfie Danger
Alfie Danger

Reputation: 469

Delete with JPA and ManyToMany

I followed this tutorial to setup a spring boot project with a login/registration system with jpa and spring security. In the tutorial code it produces a 'users', 'roles' and 'users_roles' table. Now I wanted to add a route to the controller that would delete a user by id by adding this route to the controller:

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

and added a delete method to UserService like so:

    @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);
    }

I also added a simple error controller like this:

@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;
    }

}

Now whenever I call the delete route it goes to my error page with no real message in the console. I tried adding cascade = CascadeType.ALL or REMOVE but neither work, only when starting the app now I get this exception message (app still starts):

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

How can I adapt the code from the tutorial to delete a User?

Upvotes: 3

Views: 1118

Answers (1)

SSK
SSK

Reputation: 3766

I am assuming you have an entity with a bidirectional relationship as shown below.

You need add cascade = CascadeType.ALL and orphanRemoval = true, you can also try 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;
}

Upvotes: 1

Related Questions