简体   繁体   中英

Foreign key composed of two fields one in primary key and one non primary key JPA

I'm trying to implement a weird database design and I can't figure out how to do it. There is a many to one relationship between two entities having both of them a composed primary key. The foreign key is composed of a field present in the primary key of the other entitie and a field that is not in the primary key. Hope someone could help me.

    @Entity
    @Table(name = "A")
    public class A {

            @EmbeddedId
            private Aid id;

            @JoinColumn(name = "FOREIGN_KEY_FIELD2", referencedColumnName = "foreignKeyField2")
            private B foreignKeyField2;
    }

 @Embeddable
    public class Aid{

        @JoinColumn(name = "FOREIGN_KEY_FIELD1", referencedColumnName = "foreignKeyField1")
        private B foreignKeyField1;

        private String otherField;
    }

    @Entity
    @Table(name = "B")
    public class B {

        @EmbeddedId
        private Bid id;

        @OneToMany(targetEntity = A.class, fetch = FetchType.LAZY)
        @JoinColumns({ @JoinColumn(name = "FOREIGN_KEY_FIELD1", referencedColumnName = "foreignKeyField1"),
                @JoinColumn(name = "FOREIGN_KEY_FIELD2", referencedColumnName = "foreignKeyField2") })
        private List<A> as;

    }

    @Embeddable
    public class Bid {

            private String foreignKeyField1;

            private String otherField;

    }

Best regards. Thanks in advance.

You can't solve this using @EmbeddedId you must define a IdClass.

Here is an example:

@Entity @IdClass(PartPK.class)
public class Part {
  @Id int partNo;
  @Id @ManyToOne
  Supplier supplier;
}  

public class PartPK {
  int partNo;
  int supplier;
}  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM