I am using JPA 2.0 and hibernate. I have a User class and a Group class as follows:
public class User implements Serializable {
@Id
@Column(name="USER_ID")
private String userId;
@ManyToMany
@JoinTable(name = "USER_GROUP",
joinColumns = {
@JoinColumn(name = "GROUP_ID")
},
inverseJoinColumns = {
@JoinColumn(name = "USER_ID")
}
)
private Set<Group> groupList;
//get set methods
}
public class Group
{
@Id
@Column(name="GROUP_ID")
private String groupId;
@ManyToMany(mappedBy="groupList")
private Set<User> memberList;
//get set methods
}
And then, I create a user and group and then assign the user to the group.
What I want to have is when I delete the group, the group will be deleted (of course) and all the user-group relationship that the group has will be automatically deleted from the USER_GROUP join table but the user itself is not deleted from the USER table.
With the code I have above, only the row in the GROUP table will be deleted when I delete a group and the user will still have an entry to the deleted group in the USER_GROUP join table.
If I put cascade in the User class like this:
@ManyToMany(cascade=CascadeType.ALL)
@JoinTable(name = "USER_GROUP",
joinColumns =
{
@JoinColumn(name = "GROUP_ID")
},
inverseJoinColumns =
{
@JoinColumn(name = "USER_ID")
})
private Set<Group> groupList;
When I delete the group, the user will be deleted as well!
Is there any way to achieve what I want?