如何使用 Spring 数据 JPA 和 Hibernate 添加复合外键?
How do I add composite foreign key using Spring data JPA and Hibernate?
这些是我打算在我的数据库中拥有的表。
First Table
Second Table
Third table
@Entity
@Table(name = "STATIONS")
public class Station {
@Id
private Long stnCode;
}
@Entity
@Table(name = "TRAINS")
public class Train {
@Id
private String trainNo;
}
@Entity
@Table(name = "STOPS")
public class Stop {
@EmbeddedId
private StopId stopId;
}
@Embeddable
class StopId implements Serializable {
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "TRAIN_NO")
private Train trainNo;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "STN_CODE")
private Station stnCode;
}
Hibernate: create table STATIONS (stnCode bigint not null, primary key (stnCode))
Hibernate: create table STOPS (STN_CODE bigint not null, TRAIN_NO varchar(255) not null, primary key (STN_CODE, TRAIN_NO))
Hibernate: create table TRAINS (trainNo varchar(255) not null, primary key (trainNo))
Hibernate: alter table STOPS add constraint FK1431wv4cp0qef8drx65we3m03 foreign key (STN_CODE) references STATIONS
Hibernate: alter table STOPS add constraint FK5omkrq9vt17i1w6qose6njvhw foreign key (TRAIN_NO) references TRAINS
这些是我打算在我的数据库中拥有的表。
First Table
Second Table
Third table
@Entity
@Table(name = "STATIONS")
public class Station {
@Id
private Long stnCode;
}
@Entity
@Table(name = "TRAINS")
public class Train {
@Id
private String trainNo;
}
@Entity
@Table(name = "STOPS")
public class Stop {
@EmbeddedId
private StopId stopId;
}
@Embeddable
class StopId implements Serializable {
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "TRAIN_NO")
private Train trainNo;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "STN_CODE")
private Station stnCode;
}
Hibernate: create table STATIONS (stnCode bigint not null, primary key (stnCode))
Hibernate: create table STOPS (STN_CODE bigint not null, TRAIN_NO varchar(255) not null, primary key (STN_CODE, TRAIN_NO))
Hibernate: create table TRAINS (trainNo varchar(255) not null, primary key (trainNo))
Hibernate: alter table STOPS add constraint FK1431wv4cp0qef8drx65we3m03 foreign key (STN_CODE) references STATIONS
Hibernate: alter table STOPS add constraint FK5omkrq9vt17i1w6qose6njvhw foreign key (TRAIN_NO) references TRAINS