JPA如何制作复合主键的复合外键部分

时间:2015-07-13 14:08:36

标签: java hibernate jpa

我有以下表格如何将它们映射到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
}

Event表与Meeting表具有一对多的关系。我如何在JPA中映射这种双向关系?

2 个答案:

答案 0 :(得分:14)

@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节中讨论。

答案 1 :(得分:4)

@Entity
public class Event {

    @EmbeddedId
    private EventId id;

    @OneToMany(mappedBy = "event")
    private List<Meeting> meetings = new ArrayList<>();
}

@Embeddable
public class EventId implements Serializable {

    @Column(name = "EventID")
    private Long eventId;

    @Column(name = "SourceID")
    private Long sourceId;

    //implements equals and hashCode
}

@Entity
public class Meeting {

    @EmbeddedId
    private MeetingId id; 

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

@Embeddable
public class MeetingId implements Serializable {

    @Column(name = "MeetingID")
    private Long meetingId;

    private EventId eventId;

    //implements equals and hashCode
}

您可能需要查看类似的question以获取更多详细信息。