Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define composite primary key on JPA Entity

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),
);
like image 537
Oleg Leinov Avatar asked Aug 31 '25 16:08

Oleg Leinov


1 Answers

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;
    }
}
like image 92
Andrii Avatar answered Sep 02 '25 07:09

Andrii