Hibernate - Composite Primary Key contains Foreign Key

后端 未结 1 1994
梦毁少年i
梦毁少年i 2021-01-24 22:30

I have a similar question as below, but the solution didn\'t solve my problem.

hibernate composite Primary key contains a composite foreign key, how to map this

相关标签:
1条回答
  • 2021-01-24 22:54

    Assuming f1 and F2 uniquely identify A and exist within APK, you can use JPA 2.0's derived IDs for this in a few ways. Easiest to show would be:

    @Entity
    @IdClass(BPK.class)
    public class B {
      @ID
      String f5;
      @ID
      String f6;
      @ID
      @ManyToOne(fetch=FetchType.EAGER)
      @JoinColumns({
        @JoinColumn(name="f1", referencedColumnName="f1", nullable=false),
        @JoinColumn(name="f2", referencedColumnName="f2", nullable=false)
      })
      A a;
    }
    
    public class BPK {
      String f5;
      String f6;
      APK a;
    }
    

    Key points here are that B has a reference to A that control the foriegn key fields f1 and f2, and A's primary key is used within B's primary key - with the same name as the relationship. Another way to map it would be to make B's PK an embeddid id, but embedded IDs still cannot have reference mappings, so it might look:

    @Entity
    @IdClass(BPK.class)
    public class B {
      @EmbeddedId
      BPK pk;
      @MapsId("apk")
      @ManyToOne(fetch=FetchType.EAGER)
      @JoinColumns({
        @JoinColumn(name="f1", referencedColumnName="f1", nullable=false),
        @JoinColumn(name="f2", referencedColumnName="f2", nullable=false)
      })
      A a;
    }
    
    @Embeddable
    public class BPK {
      String f5;
      String f6;
      APK apk;
    }
    

    Notice the mapsId - this tells JPA that the columns in the embedded 'apk' reference use the foreign key fields from the reference mapping as pulled from A. JPA will populate the foreign keys for you from the reference mapping, important if you are using sequencing.

    0 讨论(0)
提交回复
热议问题