likebutter likebutter - 1 month ago 11
Java Question

JPA, Hibernate, Java. Composite primary key, one of them is also foreign key

I have a problem described shortly in the title. Can anyone tell me, how can I get the same database using JPA?

create table ALBUM
(
IdAlbum int,
AlbumName varchar(35) not null,
UrlOfAlbum varchar(60) not null,
Primary Key(IdAlbum)
);
create table ARTIST
(
IdArtist int,
ArtistName varchar(35) not null,
Primary Key(IdArtist)
);
create table TRACK
(
IdTrack int,
IdAlbum int,
IdArtist int,
TrackName varchar(35) not null,
Primary Key(IdTrack, IdAlbum),
Foreign Key(IdAlbum) references Album(IdAlbum),
Foreign Key(IdArtist) references Artist(IdArtist)
);

Answer

Just put the columns into embedded key and keep relationship in the main class:

@Embeddable
class TrackId
{
    private Integer idAlbum;
    private Integer idTrack;
    // getters, setters, equals and hashCode
}

@Entity
class Track
{
     @EmbeddedId
     TrackId trackId;

     @ManyToOne
     @MapsId("idAlbum")
     @JoinColumn(name = "idAlbum", referencedColumnName = "idAlbum")
      private Album album = null;

      ....
}