Java JPA如何制作复合主键的复合外键部分
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31385658/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JPA how to make composite Foreign Key part of composite Primary Key
提问by suraj bahl
I have following tables how can i map them to JPA entities:
我有下表如何将它们映射到 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
}
The Event table has one-to-many relationship with Meeting table. How can i map this bi-directional relationship in JPA?
Event 表和 Meeting 表是一对多的关系。如何在 JPA 中映射这种双向关系?
采纳答案by Brian Vosburgh
@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.
在 JPA 2.1 规范第 2.4.1 节中讨论。
回答by Dragan Bozanovic
@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 questionfor more details.
您可能想查看一个类似的问题以获取更多详细信息。