您好我正在学习hibernate并尝试继续使用数据库。但是我遇到了问题。我有一个User实体,并成功创建了表。下一个要求是用户可以与其他用户成为朋友。友谊是双向的。用户可以拥有零个或多个朋友。我的方法是使用一对多关系,因为用户可以将多个用户作为朋友。如果我的方法有误,请纠正我。我使用了一组用户,因为它更容易维护索引,因为数组列表可以很好地工作。我可以将一个朋友添加到列表中,但是当我尝试从URL中获取某个用户时,它不会显示好友列表。并且在添加来自某个id的朋友之后,如果我尝试添加另一个朋友,它抱怨不能使用id 1的重复密钥。请问我做错了什么。我的想法是错的。这是多对多的关系吗?
用户类:
@Entity
@Table(name = "User")
public class User {
@Id
@Column(name="user_Id")
@GeneratedValue
private long id;
@Column(unique = true)
private String email;
private String first_name, last_name, description;
@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinTable(name="Friendship")
@JoinColumns({
@JoinColumn(name="userOne_Id", referencedColumnName ="user_Id"),
@JoinColumn(name="user2Id", referencedColumnName = "user_Id")})
@JsonIgnore
Collection<User> friends = new ArrayList<User>();
public Collection<User> getFriends() {
return friends;
}
public void setFriends(Collection<User> friends) {
this.friends = friends;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getFirst_name() {
return first_name;
}
public void setFirst_name(String first_name) {
this.first_name = first_name;
}
public String getLast_name() {
return last_name;
}
public void setLast_name(String last_name) {
this.last_name = last_name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
创建好友的实施:
public User createFriends(long id1, long id2){
Session session = null;
Transaction transaction = null;
User p1=null, p2=null;
try{
session = sessionFactory.openSession();
transaction = session.beginTransaction();
p1 = session.get(User.class, id1);
if(p1!=null){ //checks to see if the user exist
p2 = session.get(User.class, id2);
if(p2!=null) { //checks to see if the friend exist
if(!(p1.getFriends().contains(p2))){
//add user2 to user1 and vice versa..
p1.getFriends().add(p2);
p2.getFriends().add(p1);
session.save(p1);
session.save(p2);
transaction.commit();
}
else{
//don't do anything friend is already in the list..
}
}
else {
return p2; //return null id doesn't exist
}
}
else{
return p1; // id1 doesn't exist
}
}
catch (HibernateException ex){
if(transaction!=null)
transaction.rollback();
}
finally {
if(session!=null)
session.close();
}
return p1; //returns the user
}
检索特定用户:即使ID存储在数据库中,也无法检索和显示好友列表。
public User findById(long id) {
User user = null;
Session session = null;
Transaction transaction = null;
try {
session = sessionFactory.openSession();
transaction = session.beginTransaction();
user = session.get(User.class, id);
//to test and see if it works
System.out.println("Friends Size: "+user.getFriends().size());
}
catch(HibernateException ex) {
if(transaction!=null)
transaction.rollback();
ex.printStackTrace();
}
finally {
if(session!=null)
session.close();
}
return user;
}