Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@OneToOne make primary key as foreign key at the same time (Spring JPA/Hibernate)

I've an entity like this:

@Entity
public class Person {

    @Id
    private Long id;

    private String firstName;

    // Getters and setters
}

The id is not autogenerated, but decided by the user.

I have a second entity like this:

@Entity
public class PersonDetail {

    @Id
    @OneToOne
    private Long id; // should be referred to id of Person entity
    // or maybe private Person person; ???

    private String language;
    private Integer age;

    // Getters and setters
}

Also in the second entity, the id is not autogenerated.

I would like to make a @OneToOne relationship, and I would like that the id of PersonDetail is the primary key of PersonDetail but at the same time it must be a foreign key to the Person entity (id field).

Is it possible with Spring JPA / Hibernate annotations ?

Thanks a lot, Andrea

like image 463
Andrea Bevilacqua Avatar asked Oct 05 '17 18:10

Andrea Bevilacqua


Video Answer


1 Answers

You can follow this wiki: Primary Keys through OneToOne and ManyToOne Relationships

Re-write your PersonDetail entity to this:

@Entity
public class PersonDetail {

    @Id
    private Long id;

    @OneToOne
    @PrimaryKeyJoinColumn
    private Person person;

    private String language;
    private Integer age;

    // Getters and setters
}
like image 176
Ish Avatar answered Sep 22 '22 13:09

Ish