我有两个实体:用户和包含(引用)用户的访客。 用户:
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private long user_id;
@Column(unique = true)
private String email;
@Column
private String password;
@Column
private String name;
@Column
private String surname;
....
}
旅客:
@Entity
public class Guest {
@Id
@OneToOne
@JoinColumn(name = "user_id_fk")
private User user;
private int visits;
...
}
您可以猜到,我希望我的外键user_id(user_id_fk)是我的guest虚拟机的主键,但此代码似乎不起作用。 任何帮助将不胜感激。
答案 0 :(得分:1)
@PrimaryKeyJoinColumn
可能有用(我不确定)
您的客座课程:
@Entity
public class Guest {
@OneToOne
@PrimaryKeyJoinColumn
private User user;
private int visits;
...
}
但你应该寻找实施inheritance
答案 1 :(得分:0)
提及@JoinColumn中的列名而不是外键约束名。
@OneToOne
@JoinColumn(name = "user_id")
private User user;
答案 2 :(得分:0)
感谢Y. Tarion,我能够解决我的问题。
对于可能会觉得有帮助的人,我在这里发布我的代码:
用户:
@Entity
@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
public class User {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private long user_id;
@Column(unique = true)
private String email;
@Column
private String password;
@Column
private String name;
@Column
private String surname;
//...constructors, getters and setters...
}
旅客:
@Entity
public class Guest extends User {
private int visits;
@ManyToMany
private List<Guest> friends;
public int getVisits() {
return visits;
}
public void setVisits(int visits) {
this.visits = visits;
}
public List<Guest> getFriends() {
return friends;
}
public void setFriends(List<Guest> friends) {
this.friends = friends;
}
}