我有一个用户类。一个用户可以是许多其他用户的 friend 。这种关系是相互的。如果 A 是 B 的 friend ,那么 B 是 A 的 friend 。此外,我希望每个关系都存储额外的数据 - 例如两个用户成为 friend 的日期。所以这是同一个表上的多对多关系,带有额外的列。我知道应该创建一个中间类友谊(包含两个用户 ID 和日期列)。但是我在用 Hibernate 映射这个方面做得不够。阻止我的是映射是到同一个表。如果多对多关系在两个不同的表之间,我可以解决它。
最佳答案
你说过
many-to-many relationship on the same table
这不是一个好主意。维持下去是一场噩梦。
试试这个
@Entity
public class Friend {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Integer friendId;
@Column
private String name;
@OneToMany(mappedBy="me")
private List<MyFriends> myFriends;
}
@Entity
public class MyFriends {
@EmbeddedId
private MyFriendsId id;
@Column
private String additionalColumn;
@ManyToOne
@JoinColumn(name="ME_ID", insertable=false, updateable=false)
private Friend me;
@ManyToOne
@JoinColumn(name="MY_FRIEND_ID", insertable=false, updateable=false)
private Friend myFriend;
@Embeddable
public static class MyFriendsId implements Serializable {
@Column(name="ME_ID", nullable=false, updateable=false)
private Integer meId;
@Column(name="MY_FRIEND_ID", nullable=false, updateable=false)
private Integer myFriendId;
public boolean equals(Object o) {
if(o == null)
return false;
if(!(o instanceof MyFriendsId))
return false;
MyFriendsId other = (MyFriendsId) o;
if(!(other.getMeId().equals(getMeId()))
return false;
if(!(other.getMyFriendId().equals(getMyFriendId()))
return false;
return true;
}
public int hashcode() {
// hashcode impl
}
}
}
问候,
关于hibernate - 同一个表上的多对多与附加列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1831186/