likebutter likebutter - 3 months ago 16
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)


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;