[英]How to use foreign id as primary id in spring boot jpa?
Is there a way to use primary key of another entity as primary key without using Embeddable or Id class. 有没有一种方法可以使用另一个实体的主键作为主键,而无需使用Embeddable或Id类。 eg:
例如:
@Table(name = "employee")
@Entity
public class Employee implements Serializable {
@Id
@JoinColumn(name = "person_id")
private Person person;
Here, Person is another entity and and person_id is the primary key. 在这里,Person是另一个实体,person_id是主键。 Thanks in advance
提前致谢
Yes, if this is the only paramter constructing the PK you can do it like this 是的,如果这是构造PK的唯一参数,则可以这样做
public class Employee implements Serializable {
@Id
@Column(name="person_id")
private Long personId;
@JoinColumn(name = "person_id")
private Person person;
But if this is the case there is no use of doing it, if Employee has the same primary key then they should be in the same table, no need to separate them in 2 tables. 但是,如果是这种情况,则无需使用它,如果Employee具有相同的主键,则它们应位于同一表中,而无需将它们分成2个表。
In case we are dealing with composite primary key which contains person then we need to create an embedable key: 如果我们正在处理包含人员的复合主键,那么我们需要创建一个可嵌入的键:
@Embeddable
public class CompositeKey{
@Column(name="person_id")
private Long personId;
... // other attributes
}
public class Employee implements Serializable {
@EmbeddedId CompositeKey employeeId;
@JoinColumn(name = "person_id")
private Person person;
Another note, where is your relation annotation, you should be have OneToOne annotation on your person reference : 另一个要注意的地方,您的关系注释在哪里,您的个人参考上应该有一个OneToOne注释:
@OneToOne
@JoinColumn(name = "person_id")
private Person person;
For me it seems that Employee
could extend Person
? 对我来说,
Employee
似乎可以扩展Person
? If this is the case then with inheritance it goes in a 'natural' way. 如果是这种情况,则继承会以“自然”方式进行。
@Entity
@Inheritance(strategy=InheritanceType.JOINED)
public class Person implements Serializable {
@Id
@GeneratedValue
@Getter
private Long id;
}
@Entity
public class Employee extends Person implements Serializable {
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.