1

So i have a MyUser entity which refers to a Role entity with a many to many relationship. But when i try to delete the user, i always get the errror that the user_id is always referenced on the user_role jointable...

I have already tried every cascade type... but didn't get the solution Please help Thanks

@Table(name = "users")
public class MyUser {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    
    ... Other properties ...

    @ManyToMany
    @JoinTable(
            name = "users_roles",
            joinColumns = @JoinColumn(
                    name = "user_id", referencedColumnName = "id"),
            inverseJoinColumns = @JoinColumn(
                    name = "role_id", referencedColumnName = "id"))
    private Collection<Role> roles;

// getters setters

}


@Entity
@Table(name = "roles")
public class Role {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;

    private String role;

// getters setters
}
akbar khan
  • 13
  • 2
  • maybe this helps: https://stackoverflow.com/questions/306144/jpa-cascadetype-all-does-not-delete-orphans – Jens Dec 18 '20 at 10:43

1 Answers1

2

As it stated in the documentation:

For @ManyToMany associations, the REMOVE entity state transition doesn’t make sense to be cascaded because it will propagate beyond the link table. Since the other side might be referenced by other entities on the parent-side, the automatic removal might end up in a ConstraintViolationException.

So, before removing Role entity you should be assured that there is no MyUser entity linked with this role.

SternK
  • 11,649
  • 22
  • 32
  • 46