I've done research on how to make recursive relationships and I already know how to do them, but I can't avoid redundancy in this type of relationship. I have a User class that has a "friends" attribute. The User can be friends with many other Users, and other Users can be friends with one. So I did the following:
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "friends",
joinColumns = @JoinColumn(name = "user1_id"),
inverseJoinColumns = @JoinColumn(name = "user2_id"))
private List<User> friends = new ArrayList<User>();
To enter the data, I use the following service function.
public void addFriend(User requester, User requested) throws DataNotFoundException{
requester.getFriends().add(requested);
requested.getFriends().add(requester);
update(requested);
}
Every time I update the "requested", it fetches the entity that relates to it "requester" and updates it as well. Initially I thought it was a Cascade problem, but I saw that Cascade default is disabled, and all options are different ways to propagate operations to children.
In the end this creates 2 rows in my table with redundant data
user1_id | user2_id
1 2
2 1
I want to create just one line that is used by both sides of the relationship.
I've thought about creating a custom query for this, but it doesn't seem like the most appropriate solution from a design point of view. Because it would create a snowball of customizations that I would need to do.
Edit: When I remove getFriends().add() from either side the result is the same. The code also seems to be redundant as I'm trying this kind of relationship for the first time, and I did it the same way I would with other bidirectional many-to-many relationships