简体   繁体   中英

JPA how to make composite Foreign Key part of composite Primary Key

I have following tables how can i map them to JPA entities:

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
}

The Event table has one-to-many relationship with Meeting table. How can i map this bi-directional relationship in JPA?

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

Discussed in JPA 2.1 spec, section 2.4.1.

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

You may want to take a look at a similar question for more details.

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