likebutter likebutter - 1 year ago 101
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 Source

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

class TrackId
    private Integer idAlbum;
    private Integer idTrack;
    // getters, setters, equals and hashCode

class Track
     TrackId trackId;

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download