Question

I have a person Entity and two list of persons in it, that i implemented this way (thanks to this post : Hibernate many-to-many association with the same entity) :

@ManyToMany
@JoinTable(name="tbl_friends",
 joinColumns=@JoinColumn(name="personId"),
 inverseJoinColumns=@JoinColumn(name="friendId")
)
private List<User> friends;

@ManyToMany
@JoinTable(name="tbl_friends",
 joinColumns=@JoinColumn(name="friendId"),
 inverseJoinColumns=@JoinColumn(name="personId")
)
private List<User> friendOf;

But, with the @ManyToMany annotation the Cascadings (MERGE,DELETE,etc..) doesn't work. Is there a way to achieve the same mapping but with enabling Cascadings ?

Was it helpful?

Solution

Cascadings do work with many-to-many associations. But most of the time, there shouldn't be any cascade set on a many-to-many association: since a friend is a friend of many persons, you can't, for example, delete all John's friends (Paul and Matt) when you delete John. Indeed, many other people (Jack, Sarah) also have Paul and Matt as friends, and it would thus lead to a constraint violation.

The problem with your code is that the mapping is wrong. You have a single, bidirectional, many-to-many association here, but you mapped it as two unidirectional many-to-many associations, using the same join table.

In a bidirectional association, one side must be the inverse side. If you choose friendOf as the inverse side, it should thus be mapped as

@ManyToMany(mappedBy = "friends")
private List<User> friendOf;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top