I am trying to design some kind of user to user relationship, such as "user A follows user B" and "User A wants to be User B s friend".
我有一个用户类别,设计方式就是这样:
@Entity
public class User{
@OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER)
List<User> followers;
@OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER)
List<User> following;
@OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER)
List<User> friendRequests;
@OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER)
List<User> requesting;
@OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER)
List<User> friends;
}
我有两个问题:
- Hibernate is giving me cannot simultaneously fetch multiple bags problem
- I have looked up online, people said to remove FetchType.EAGER or change it to Set instead of List, but that resulted me Field doesn t have a default value
我感觉到,关系没有适当界定,我也应当看到更多的表格,因为现在我只看到用户表和用户——用户表格。
Update
The following creates 3 table, friends, followers, and requesters. Is this somewhat optimized compared to 5 tables? And are there any advantage to this in comparison with what Mr.J4mes suggested?
@ManyToMany
@JoinTable(name = "followers", joinColumns = @JoinColumn(name = "followerId"), inverseJoinColumns = @JoinColumn(name = "userId"))
private List<User> followers;
@ManyToMany
@JoinTable(name = "followers", joinColumns = @JoinColumn(name = "userId"), inverseJoinColumns = @JoinColumn(name = "followerId"))
private List<User> following;
@ManyToMany
@JoinTable(name = "friends", joinColumns = @JoinColumn(name = "userId"), inverseJoinColumns = @JoinColumn(name = "friendId"))
private List<User> friends;
@ManyToMany
@JoinTable(name = "requesters", joinColumns = @JoinColumn(name = "requesterId"), inverseJoinColumns = @JoinColumn(name = "userId"))
private List<User> friendRequests;
@ManyToMany
@JoinTable(name = "requesters", joinColumns = @JoinColumn(name = "userId"), inverseJoinColumns = @JoinColumn(name = "requesterId"))
private List<User> requesting;