两个外键作为主键 [英] Two foreign keys as primary key
本文介绍了两个外键作为主键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用休眠注释实现以下表格?
How would I implement the following tables using hibernate annotations?
当前代码为:(为简洁起见)
用户
@Entity
@Table(name = "user")
public class User implements java.io.Serializable {
@Id
@GeneratedValue
public Long getId() {
return id;
}
}
社交网络
@Entity
@Table(name = "social_network")
public class SocialNetwork implements java.io.Serializable {
@Id
@GeneratedValue
public int getId() {
return id;
}
}
SocialProfile
@Entity
@Table(name = "social_profile")
public class SocialProfile implements java.io.Serializable {
@Id
@ManyToOne
@JoinColumn(name="user_id")
public User getUser() {
return user;
}
@Id
@ManyToOne
@JoinColumn(name="social_network_id")
public SocialNetwork getSocialNetwork() {
return socialNetwork;
}
}
很明显,我的代码目前无法正常工作.任何人都可以对此有所了解吗?
Obviously my code is not working correctly right now. Can anyone shed some light onto this?
推荐答案
您需要这样的可嵌入的SocialProfileId:
you need an embeddable SocialProfileId like this :
@Embeddable
public class SocialProfileId implements Serializable {
@Column(name = "user_id")
private long userId;
@Column(name = "social_network_id")
private long socialNetworkId;
}
然后,您的SocialProfile实体将如下所示:
then, your SocialProfile entity will look like this :
@Entity
@Table(name = "social_profile")
public class SocialProfile implements java.io.Serializable {
@EmbeddedId
private SocialProfileId id;
@ManyToOne
@JoinColumn(name="user_id")
public User getUser() {
return user;
}
@ManyToOne
@JoinColumn(name="social_network_id")
public SocialNetwork getSocialNetwork() {
return socialNetwork;
}
}
编辑抱歉,我在答案中的字段和方法上使用了混合注释...绝对不要这样做! ;-)
EDIT sorry, i have mixed annotations on fields and methods on my answer ... never do that ! ;-)
这篇关于两个外键作为主键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文