I created relation @ManyToMany with the same entity.
Here is my entity:
@Entity
@Table(name = "user")
public class User extends BaseEntity implements Serializable {
...
@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "table_friends", joinColumns =
@JoinColumn(name = "userId"), inverseJoinColumns =
@JoinColumn(name = "friendId"))
private List<User> friends;
@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "table_friends", joinColumns =
@JoinColumn(name = "friendId"), inverseJoinColumns =
@JoinColumn(name = "userId"))
private List<User> friendsof;
I created a few “users” and added them to friend list:
User u1 = new User();
User u2 = new User();
User u3 = new User();
u1.getFriends().add(u2);
u1.getFriendsof().add(u2);
u1.getFriends().add(u3);
u1.getFriendsof().add(u3);
When I remove a friend from the list u1.getFriends().remove(u3), everything is ok . But when I want to delete the user from the database u3.remove(), friends of u1 still are the same, although already in the database list of friend is correct.
- Can I somehow refresh the list after removing a user?
- And if so, how can I know which list of friend I need to refresh?
Edit: Also seems to me that I should remove the (cascade = CascadeType.ALL), because when I remove u1, removes all paired members. Is this the correct behavior?
Hmm, why do you need 2 list
friendsandfriendsOf? If you’re my friend, isn’t it obvious that I am your friend?Besides, if you only want to end the relationship between 2
User, you should useu1.getFriends().remove(u3).Lastly, if you want to remove a user. You should create an
EntityManager emand execute the commandem.remove(u3). This command will delete u3 as well as the relationship. However, you should be careful withcascade = CascadeType.ALL. This cascadeType means that if you remove u3, u1 will also be removed. I think you should leave it@ManyToManywithout cascade.