2012-04-23 49 views
3

我有以下的情況來解決,但不能得到它的工作(嘗試和Hibernate的EclipseLink):JPA:在嵌入類的外鍵

Table_1: 
    Column_A is Primary Key 
    ... some other columns do follow 

Table_2: 
Column_x is Primary Key and is Foreign Key to Table_1.Column_A 
Column_y is Primary Key and is Foreign Key to Table_1.Column_A 
Column_z is Primary Key 

因此,表2具有複合主鍵。

我試圖去實現它的方式如下:

class Table_1 { 
    @Id int Column_A; 
} 

class Table_2 { 
    @EmbeddedId PK key; 

    @Embeddable class PK { 
    @OneToOne(targetEntity=Table_1.class) 
    @JoinColumn(name="Column_x",referencedColumnName="Column_A") 
    int Column_x; 

    @OneToOne(targetEntity=Table_1.class) 
    @JoinColumn(name="Column_y",referencedColumnName="Column_A") 
    int Column_y; 

    int Column_z; 

    public boolean equals(Object O) { ... } 
    public int hashCode() { ... } 
    } 
} 

但是,當我運行時,我從EclipseLink得到的提示在@Embeddable中,我可能只使用「基本」註釋。因此,我的問題是如何解決上述情況?

我沒有訪問類Table_1的源代碼,但必須按原樣使用它。另外,很可能會有更多的類/表建立到Table_1的外鍵。

回答

1

使用@IdClass。

見, http://en.wikibooks.org/wiki/Java_Persistence/Identity_and_Sequencing#JPA_2.0

@IdClass(PK.class) 
class Table_2 { 
    @Id 
    @OneToOne(targetEntity=Table_1.class) 
    @JoinColumn(name="Column_x",referencedColumnName="Column_A") 
    Table_1 Column_x; 

    @Id 
    @OneToOne(targetEntity=Table_1.class) 
    @JoinColumn(name="Column_y",referencedColumnName="Column_A") 
    Table_1 Column_y; 

    @Id 
    int Column_z; 

    public boolean equals(Object O) { ... } 
    public int hashCode() { ... } 
    } 
} 

class PK { 
    int Column_x; 
    int Column_y; 
    int Column_z; 
} 
0

你有權使用@EmbeddedId(而不是@IdClass,這是更比外鍵生成的ID)。我認爲你的問題是,當他們實際上應該被鍵入到Table_1或Table_2類時,你將這些FKs聲明爲整數。