It is very common pattern, that we have join table for many-to-many relationships:
CREATE TABLE user (
id BIGINT PRIMARY KEY
);
CREATE TABLE role (
id BIGINT PRIMARY KEY
);
CREATE TABLE user_roles (
user_id BIGINT NOT NULL REFERENCES user(id) ON DELETE CASCADE,
role_id BIGINT NOT NULL REFERENCES role(id) ON DELETE CASCADE,
PRIMARY KEY(user_id, role_id)
);
It is obvious that if you delete user or role, you don't want to hold this relationship. Unfortunately when using Hibertnate:
@Entity
public class User {
@ManyToMany(mappedBy = "users")
private Set<Role> roles = new HashSet<>();
}
@Entity
public class Role {
@ManyToMany
@JoinTable(name = "user_role",
joinColumns = @JoinColumn(name = "role_id", ),
inverseJoinColumns = @JoinColumn(name = "user_id")
)
private Set<User> users = new HashSet<>();
}
it is impossible to indicate this "ON DELETE" behavior. (Of course I can not use CascadeType.REMOVE, because it will delete whole Role/User entity not just relationship) could you please make @OnDelete possible for JoinTable? Thank you in advance |