Hi Rob,
Not sure if you wanted JPA 2 examples of composite PKs or just regular JPA examples. The JPA 2 spec goes quite a lot further in composite primary keys, and it gets quite hairy when you follow the path all the way to its inner dark corners. None of the examples in the earlier post actually showed any JPA 2 examples, they were just JPA 1.0 examples. If you are interested in a couple of simple examples of JPA 2, the most common case is that of having a @ManyToOne relationship as part of an entity PK.
So we have a CompactDisc that has a title and a relationship to an Artist. The key is on both the title and the artist.
@Entity @IdClass(CompactDiscPK.class)
public class CompactDisc {
@Id
String title;
@Id @ManyToOne Artist artist;
//...
}
public class CompactDiscPK {
public String title;
public int artist;
// ...
}
@Entity
public class Artist {
@Id int id;
// ...
}
Note that we can now use the @Id annotation on the many-to-one relationship. The PK class has attributes that are named the same as those on the CompactDisc class, but in the case of the "artist" field, the attribute of the PK class is not of type Artist, but of type int, which is the type of the PK of Artist. This is much easier to map than it used to be in JPA 1.0, when you had to create a second redundant field in CompactDisc and map it as read-only.
The second example is when you want to map the PK in CompactDisc as an embedded id:
@Entity
public class CompactDisc {
@EmbeddedId CompactDiscPK id;
@ManyToOne @MapsId Artist artist;
//...
}
@Embedded
public class CompactDiscPK {
public String title;
public int artist;
// ...
}
In this example the "artist" field in the embeddable CompactDiscPK class is actually being mapped by the ManyToOne artist field in CompactDisc. The new @MapsId annotation allows this to happen. The default join column (ARTIST_ID) will apply in both examples. Neat, eh?