These are the tables I intend to have in my database.
Asked
Active
Viewed 259 times
-1
-
1Does this answer your question? [JPA how to make composite Foreign Key part of composite Primary Key](https://stackoverflow.com/questions/31385658/jpa-how-to-make-composite-foreign-key-part-of-composite-primary-key) – Mehdi Rahimi May 17 '22 at 12:29
1 Answers
0
@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

Ivan Zbykovskyi
- 71
- 5
-
1Thanks. Can you explain why the embeddable class has to implement Serializable? – wetpaddyfield May 17 '22 at 15:20
-
In another case you`ll have the Exception - Caused by: jakarta.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.MappingException: Composite-id class must implement Serializable: StopId – Ivan Zbykovskyi May 17 '22 at 16:15