【问题标题】:How to make Composite Primary Key Using Two Foreign key?如何使用两个外键制作复合主键?
【发布时间】:2018-11-19 13:09:38
【问题描述】:

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

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

表2

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

表3

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;
  }


 }

}

【问题讨论】:

    标签: hibernate jpa spring-data-jpa


    【解决方案1】:

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

    @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;
    
        // ...
    }
    

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

    【讨论】:

    • 感谢您的评论。这是非常有帮助的。但是当我尝试保留这个Table3 实体时遇到了问题。它说Could not set field value [15] value by reflection....。你能帮我解决这个问题吗
    猜你喜欢
    • 1970-01-01
    • 2012-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-24
    相关资源
    最近更新 更多