使用 JPA 2.0 的 Self ManyToMany 和附加列
我想在用户模型之间创建一种“友谊”关系。我还需要为每一个友谊增加一个专栏。我知道我需要使用带有复合主键的连接类。这是我的 User 类,
public class User implements Serializable {
@Id
@Basic(optional = false)
@Column(name = "id")
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
@OneToMany(mappedBy="friendA")
private Set<Friendship> friends;
我也有 FriendshipId 类
@Embeddable
public class FriendshipId implements Serializable {
private long friendAId;
private long friendBId;
}
,最后是 Friendship 类,
@Entity
@IdClass(FriendshipId.class)
public class Friendship implements Serializable {
private Integer friendAId;
private Integer friendBId;
@Basic(optional = false)
@Column(name="date_added")
@Type(type="org.jadira.usertype.dateandtime.joda.PersistentDateTime")
private DateTime date_added;
@ManyToOne
@PrimaryKeyJoinColumn(name="friendAId", referencedColumnName="friendAId")
private User friendA;
@ManyToOne
@PrimaryKeyJoinColumn(name="friendBId", referencedColumnName="friendBId")
private User friendB;
}
这似乎可行,但我的数据库中生成的数据库表包含每个 ID 两次 - 我猜一组用于主键,第二组用于外键。
我怎样才能让这个PK变得独特——如果有B对A的友谊,A对B的友谊就会被拒绝?
另一个问题是关于设计的——这是实现我想要实现的目标的好方法吗?我的意思是使用复合密钥而不是简单地使用自己的 pk 来建立友谊。
I want to create kind of "Friendship" relation between Users models. I also need an additional columns for every friendship. I know I need to use joining class with composite primary key. Thats my User class
public class User implements Serializable {
@Id
@Basic(optional = false)
@Column(name = "id")
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
@OneToMany(mappedBy="friendA")
private Set<Friendship> friends;
I also have FriendshipId class
@Embeddable
public class FriendshipId implements Serializable {
private long friendAId;
private long friendBId;
}
And finally Friendship class
@Entity
@IdClass(FriendshipId.class)
public class Friendship implements Serializable {
private Integer friendAId;
private Integer friendBId;
@Basic(optional = false)
@Column(name="date_added")
@Type(type="org.jadira.usertype.dateandtime.joda.PersistentDateTime")
private DateTime date_added;
@ManyToOne
@PrimaryKeyJoinColumn(name="friendAId", referencedColumnName="friendAId")
private User friendA;
@ManyToOne
@PrimaryKeyJoinColumn(name="friendBId", referencedColumnName="friendBId")
private User friendB;
}
This seems to work but database table generated in my database consists every ID twice - I guess one set is for primary key and second for foreign keys.
How can I make this PK unique - that Friendship of A to B will be rejected if there is B to A one?
Another question is about a design - is this a good way to achieve what I want to achieve? I mean using composite key instead of simply own pk for Friendship.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我想在“友谊”实体中,您添加了“用户”实体两次(非常好),但为什么
又在那里?这可能是导致 ID 生成两次的原因。
I guess in Friendship entity you added User entity twice (very fine) but why
again there? That could be cause of ID getting generated twice.