[英]Define composite primary key on JPA Entity
是否可以在我的實體中定義復合主鍵,但 2 個 ID 是 @OneToOne 字段? 我正在嘗試使用 @PrimaryKeyJoinColumn 注釋來做到這一點,但沒有成功
public class EmployeeEntity {
// my composite ID must be person_id + department_id
@OneToOne
//@PrimaryKeyJoinColumn(name = "person_id")
private PersonEntity person;
@OneToOne
//@PrimaryKeyJoinColumn(name = "department_id")
private DepartmentEntity department;
// other fields
我絕對可以用兩個數字字段以經典的方式做到這一點,但我想設置一個 OneToOne 關系。
實際上,數據庫模式應該是這樣的:
create table EMPLOYEE
(
PERSON_ID INT not null,
DEPARTMENT_ID INT not null,
constraint EMPLOYEE_PK
primary key (PERSON_ID, DEPARTMENT_ID),
constraint EMPLOYEE_PERSON_ID_FK
foreign key (PERSON_ID) references PERSON (ID),
);
我相信您需要一個可嵌入的復合鍵:
@Entity
public class EmployeeEntity extends BaseEntity {
@Embeddable
static class Pk implements Serializable {
@OneToOne
@JoinColumn(name = "PERSON_ID")
private PersonEntity person;
@OneToOne
@JoinColumn(name = "DEPARTMENT_ID")
private DepartmentEntity department;
}
@Id
private final Pk id;
public EmployeeEntity(DepartmentEntity department, PersonEntity person) {
this.id = new Pk();
this.id.person = person;
this.id.department = department;
}
}
您應該創建一個包含兩個字段的新 class ,該 class 將成為您的EmployeeEntity
的復合鍵。
@Embeddable
public class EmployeeId implements Serializable {
private PersonEntity person;
private DepartmentEntity department;
public EmployeeId() {}
public EmployeeId(PersonEntity person, DepartmentEntity department) {
this.person = person;
this.department = department;
}
// equals() and hashCode() methods should also be implemented here
}
public class EmployeeEntity implements Serializable {
@EmbeddedId
private EmployeeId id;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.