如何在spring boot jpa中使用外部id作为主id?

问题描述 投票:2回答:2

有没有办法使用另一个实体的主键作为主键而不使用Embeddable或Id类。例如:

@Table(name = "employee")
@Entity
public class Employee implements Serializable {

    @Id
    @JoinColumn(name = "person_id")
    private Person person;

这里,Person是另一个实体,person_id是主键。提前致谢

java mysql spring hibernate jpa
2个回答
5
投票

是的,如果这是构建PK的唯一参数,你可以这样做

public class Employee implements Serializable {

    @Id
    @Column(name="person_id")
    private Long personId;

    @JoinColumn(name = "person_id")
    private Person person;

但是如果是这种情况就没有用它,如果Employee具有相同的主键,那么它们应该在同一个表中,不需要在2个表中将它们分开。

如果我们正在处理包含person的复合主键,那么我们需要创建一个可嵌入的键:

@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;

另一个注意事项,你的关系注释在哪里,你应该在你的人物参考上有OneToOne注释:

@OneToOne
@JoinColumn(name = "person_id")
private Person person;

1
投票

对我来说,似乎Employee可以扩展Person?如果是这种情况,那么继承就会以“自然”的方式进行。

@Entity
@Inheritance(strategy=InheritanceType.JOINED)
public class Person implements Serializable {
   @Id
   @GeneratedValue
   @Getter
   private Long id;
}

@Entity
public class Employee extends Person implements Serializable {

}
© www.soinside.com 2019 - 2024. All rights reserved.