문제

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 ?

도움이 되었습니까?

해결책

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;
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top