2014-11-04 71 views
1

我有一箇舊的數據庫中的兩個表,我試圖創建它的Java模型(使用JPA 2.0和Hibernate 4)沒有鑑別或層次OneToOne映射

create table master (
    master_id      number(38) not null, --this is the primary key 
    ... 
) 

create table child (
    master_id      number(38) not null, --the primary key and also a foreign key to master.id 
    ... 
) 

我創建了實體但是我對每個類使用哪些註釋感到困惑。 @JoinColumn? @PrimaryKeyJoinColumn? @Id

我知道Master將管理Java層的持久性。也就是說,持續更新將從Master級聯。這一定是一個基本問題,但我是JPA的新手。

@Entity 
class Master { 

    @Id 
    @Column (name="master_id") 

    @OneToOne 
    private Child child; 

} 

@Entity 
class Child { 

    @OneToOne 
    private Master master; 
} 

回答

0

見下:

@Entity 
class Master { 

    @Id 
    @GeneratedValue(strategy = GenerationType.AUTO) 
    private Long id; 

    @OneToOne(mappedBy = "master") 
    private Child child; 
} 

@Entity 
class Child { 

    @Id 
    @OneToOne 
    @JoinColumn(name = "master_id") 
    private Master master; 
} 

更多信息:

http://en.wikibooks.org/wiki/Java_Persistence/Identity_and_Sequencing#Primary_Keys_through_OneToOne_and_ManyToOne_Relationships

+0

道歉,我並不清楚,child.master_id是PK的,而不僅僅是外國鍵。我將編輯主要問題。 – Melissa 2014-11-06 14:14:19

+0

查看更新的答案。 – 2014-11-06 14:27:04

+0

它最終與@MapsId一起使用,如http://vard-lokkur.blogspot.ca/2014/05/onetoone-with-shared-primary-key.html中所建議的那樣 – Melissa 2014-11-07 16:22:26