I am using hibernate and Spring to persist data in database, (just to be sure I've tested with MySQL and MSSQL) and I am facing a strange behaviour, I'm mapping my classes this is way:
public class User extends BaseDomain implements UserDetails {
@OneToMany(mappedBy = "user", fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true)
private List<UserRole> userRole;
...
}
Child Entity:
public class UserRole extends BaseDomain implements GrantedAuthority {
@ManyToOne(optional = false, fetch = FetchType.EAGER)
@JoinColumn(name = "role_id")
private Role role;
@ManyToOne(optional = false, fetch = FetchType.EAGER)
@JoinColumn(name = "user_id")
private User user;
...
}
At this point if I try to remove an user, it is ok:
Hibernate: delete from user_role where id=?
Hibernate: delete from user where id=?
However, my problem begins when I add the second parent class:
public class Role extends BaseDomain {
@OneToMany(mappedBy = "role", cascade = CascadeType.ALL, orphanRemoval = true)
private List<UserRole> userRole;
...
}
From now on, hibernate only delete the parent (User) entity, causing an exception. Any guess on what's wrong with my mapping? Thanks in advance. OBS: Every other DB operation works fine. I also try Set<>.
UPDATE
If let my second Parent class mapped like in the below way, it works, however, now I am unable to delete the child from the Role
side, is there a way to keep the same behaviour in both sides?
@OneToMany(mappedBy = "perfil", orphanRemoval = true)
private List<UserRole> userRole;