2017-10-05 100 views
1

主鍵外鍵我有一個實體是這樣的:@OneToOne使得在同一時間(春季JPA /休眠)

@Entity 
public class Person { 

    @Id 
    private Long id; 

    private String firstName; 

    // Getters and setters 
} 

id不是自動生成的,而是由用戶決定。

我有第二個實體,像這樣:

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

而且,在第二實體中,id不會自動生成。

我想作一個@OneToOne的關係,我想是的PersonDetailidPersonDetail主鍵,但在同一時間,它必須是一個外鍵Person實體(id場)。

Spring JPA/Hibernate註釋可能嗎?

非常感謝, 安德烈

+0

本博客文章介紹如何做你想要:https://vladmihalcea.com/2016/07/26/the-best-way-to-map-a-onetoone-relationship-with-jpa-and-hibernate/ –

回答

0

你可以按照這個wiki: Primary Keys through OneToOne and ManyToOne Relationships

PersonDetail實體重新寫這個:

@Entity 
public class PersonDetail { 

    @Id 
    private Long id; 

    @OneToOne 
    @PrimaryKeyJoinColumn 
    private Person person; 

    private String language; 
    private Integer age; 

    // Getters and setters 
} 
+0

爲什麼你引入了單獨的'id'字段在'PersonDetail'中? – gavenkoa