web-dev-qa-db-fra.com

JPA comment intégrer la clé étrangère composite à la clé primaire composite

J'ai les tableaux suivants comment puis-je les mapper aux entités 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
}

La table d'événements a une relation un-à-plusieurs avec la table de réunion. Comment puis-je cartographier cette relation bidirectionnelle dans JPA?

20
suraj bahl
@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;
}

Discuté dans la spécification JPA 2.1, section 2.4.1.

20
Brian Vosburgh
@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
}

Vous voudrez peut-être jeter un oeil à un similaire question pour plus de détails.

6
Dragan Bozanovic