小编典典

JPA如何使复合外键成为复合主键的一部分

hibernate

我有以下表格如何将它们映射到JPA实体:

TABLE Event {
EventID
SourceID
....Other event fields
PK (EventID, SourceID)
}

TABLE MEETING {
MeetingID
EventID
SourceID
...Other meeting fields
PK(MeetingID,EventID, SourceID)
FK(EventID, SourceID) //FK with Event table
}

事件表与会议表具有一对多关系。如何在JPA中映射这种双向关系?


阅读 301

收藏
2020-06-20

共1个答案

小编典典

@Embeddable
public class EventID {
    public int eventID;
    public int sourceID;
}

@Entity
public class Event {
    @EmbeddedId
    public EventID id;

    @OneToMany(mappedBy="event")
    public Collection<Meeting> meetings;
}

@Embeddable
public class MeetingID {
    public EventID eventID; // corresponds to ID type of Event
    public int meetingID;
}

@Entity
public class Meeting {
    @EmbeddedId
    public MeetingID id;

    @MapsId("eventID")
    @JoinColumns({
        @JoinColumn(name="EventID", referencedColumnName="EventID"),
        @JoinColumn(name="SourceID", referencedColumnName="SourceID")
    })
    @ManyToOne
    public Event event;
}

在JPA 2.1规范的第2.4.1节中讨论。

2020-06-20