title: How to fix "violates foreign key constraint" in Spring-Boot when trying to delete a record. Using @ManyToMany
body: <p>I am trying to delete some records from my database but I recieve the following error: "update or delete on table "role" violates foreign key constraint "fk3qjq7qsiigxa82jgk0i0wuq3g" on table "users_role" "</p>
  
  <p>I did some research and I found that it might have something to do with one of my relationships being set to @ManyToMany. </p>
  
  <p>I tried modifying my code from other examples in this site but with no luck.</p>
  
  <pre class="lang-java prettyprint-override"><code>public class User {
  
      @Id
      @GeneratedValue(strategy = GenerationType.AUTO)
      @Column(name = "users_id")
      private long id;
      @Column(name = "email")
      @Email(message = "*Please provide a valid Email")
      @NotEmpty(message = "*Please provide an email")
      private String email;
      @Column(name = "password")
      @Length(min = 5, message = "*Your password must have at least 5 characters")
      @NotEmpty(message = "*Please provide your password")
      private String password;
      @Column(name = "name")
      @NotEmpty(message = "*Please provide your name")
      private String name;
      @Column(name = "surname")
      @NotEmpty(message = "*Please provide your surname")
      private String surname;
      @Column(name = "active")
      private int active;
  
      @ManyToMany(cascade = CascadeType.ALL)
      @JoinTable(name = "users_role", joinColumns = @JoinColumn(name = "users_id"), inverseJoinColumns = @JoinColumn(name = "role_id"))
      private Set&lt;Role&gt; roles;
  
      @Column(name = "position")
      private String position;
  </code></pre>
  
  <pre class="lang-java prettyprint-override"><code>public class Role {
      @Id
      @GeneratedValue(strategy = GenerationType.AUTO)
      @Column(name = "role_id")
      private int id;
  </code></pre>
  
  <pre class="lang-java prettyprint-override"><code>public class UserController {
  .
  .
  .
  .
  @GetMapping("/admin/deleteuser/{id}")
      public String deleteUser(@PathVariable("id") long id, Model model) {
          User user = userRepository.findById(Long.valueOf(id)).orElseThrow(() -&gt; new IllegalArgumentException("Invalid user Id:" + id));
  
          userRepository.delete(user);
          model.addAttribute("users", userRepository.findAll());
          return "/admin/show-users";
      }
  </code></pre>