如何使用两个外键制作复合主键?

时间:2018-11-19 13:09:39

标签: hibernate jpa spring-data-jpa

我有三个表,其中一个表正在使用其他两个表的外键来构成复合主键。现在我正在使用@Embeddable,但是由于这两个键都是外键,因此我现在将如何在实体中创建复合主键。

CREATE TABLE table1
(table1id INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY (table1id));

table2

CREATE TABLE table2
(table2id INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY (table2id));

table3

CREATE TABLE table3 (
   table1id INT NOT NULL,
   table2id INT NOT NULL,
   PRIMARY KEY (table1id, table2id),
   FOREIGN KEY (table1id) REFERENCES table1 (table1id),
   FOREIGN KEY (table2id) REFERENCES table2 (table2id)
);

如何将此表转换为Hibenate实体。

 @Entity
 @Table(name="table3")
 class Table1 {
   @Id
   long table1id;
   //getter and setter
  }

 @Entity
 @Table(name="table3")
   class Table2 {
   @Id
   long table2id;
   //getter and Setter
   }

  @Entity
  @Table(name="table3")
  class Table3 {
     @EmbeddedId
     private table3PK table3PKId;

   //getter and Setter
   }


 @Embeddable
  Class table3PK{

  @ManyToOne
   @JoinColumn(name="table1Id" ,referencedColumnName="table1id")
  Table1 table1;

  @ManyToOne
  @JoinColumn(name="table2Id" ,referencedColumnName="table2id")
  Table2 table2;

  public table3PK(){

  }

  public table3PK(Table1 table1 ,Table2 table2){
   this.table1;
   this.table2;
  }


 }

}

1 个答案:

答案 0 :(得分:0)

目前尚不清楚您遇到什么问题;但您可以尝试使用“派生身份”并像这样映射您的实体:

@Entity
public class Table1 {
    @Id
    long table1id;
    // ...
}

@Entity
public class Table2 {
    @Id
    long table2id;
    // ...
}

@Embeddable
public class Table3PK {
    long table1PK; // corresponds to PK type of Table1
    long table2PK; // corresponds to PK type of Table2
} 

@Entity
public class Table3 {
    @EmbeddedId
    private Table3PK id;

    @MapsId("table1PK") // maps table1PK attribute of embedded id 
    @ManyToOne
    Table1 table1;

    @MapsId("table2PK") // maps table2PK attribute of embedded id 
    @ManyToOne
    Table2 table2;

    // ...
}

JPA 2.2 spec的第2.4.1节中讨论了派生的身份(带有示例)。