JPA: foreign key in an embedded class

I have the following situation for the solution, but I can not get it to work (tried Hibernate and 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

Thus, table 2 has a composite primary key.

I tried to understand this as follows:

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() { ... } 
  }
}

However, when I start, I get a hint from EclipseLink that in @Embeddable I can only use "basic" annotations. So my question is how to solve the above scenario?

I do not have access to the source code of the Table_1 class, but it should use it as is. In addition, it is very likely that there may be more classes / tables setting foreign keys for Table_1.

+3
source share
2 answers

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

, @EmbeddedId ( @IdClass, , ). , , FK , Table_1 Table_2.

0

All Articles