Home > Mobile >  Define composite primary key on JPA Entity
Define composite primary key on JPA Entity

Time:12-07

Is it possible to define a composite primary key in my Entity, but 2 IDs are @OneToOne fields? I'm trying to do it with @PrimaryKeyJoinColumn annotation, unsuccessfully

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

I definitely can do it in a classic way with two numeric fields, but I want to have a OneToOne relationship to be set.

Actually, DB schema should be like that:

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),
);

CodePudding user response:

I believe an embeddable composite key is what you need:

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

CodePudding user response:

You should create a new class which contains both fields, that class will become your composite key for your 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;
}
  • Related