我有以下情况要解决,但无法使其工作(尝试过Hibernate和EclipseLink):
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建立外键。
答案 0 :(得分: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;
}
答案 1 :(得分:0)
你正确使用@EmbeddedId(而不是@IdClass,这对于生成的ID比外键更多)。我认为您的问题是,当您将这些FK实际输入到Table_1或Table_2类时,您会将这些FK声明为整数。