In this code, how to generate a Java class for the composite key (how to composite key in hibernate):
create table Time (
levelStation int(15) not null,
src varchar(100) not null,
dst varchar(100) not null,
distance int(15) not null,
price int(15) not null,
confPathID int(15) not null,
constraint ConfPath_fk foreign key(confPathID) references ConfPath(confPathID),
primary key (levelStation, confPathID)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Best Answer
To map a composite key, you can use the
EmbeddedId
or theIdClass
annotations. I know this question is not strictly about JPA but the rules defined by the specification also applies. So here they are:With an
IdClass
The class for the composite primary key could look like (could be a static inner class):
And the entity:
The
IdClass
annotation maps multiple fields to the table PK.With
EmbeddedId
The class for the composite primary key could look like (could be a static inner class):
And the entity:
The
@EmbeddedId
annotation maps a PK class to table PK.Differences:
@EmbeddedId
somehow communicates more clearly that the key is a composite key and IMO makes sense when the combined pk is either a meaningful entity itself or it reused in your code.@IdClass
is useful to specify that some combination of fields is unique but these do not have a special meaning.They also affect the way you write queries (making them more or less verbose):
with
IdClass
with
EmbeddedId
References