JPA Composite Primary Key

Here is an example of a composite primary key object for Hibernate/ JPA. It makes things more complicated by creating a relation from one of the pk fields to another entity. If we didn’t have this extra relation then the inner class would have another simple @Column instead.

@Table(name="MY_TABLE" )
public class Test implements Serializable, Validatable
	public Test(){}

	PK id;

        //other fields
	public static class PK implements Serializable{
		public PK (){}
		@Column (name="PK_1")
		private Long pk1;
		private AnotherEntity ent;

		public boolean equals(Object obj) {
	        if (obj == this) return true;
	        if (obj == null) return false;
	        if (!(obj instanceof PK )) return false;
	        PK pk = (PK) obj;
	        if (pk.ent == null && pk.pk1 == null) return false;
	        return new EqualsBuilder().append(pk1, pk.pk1).append( ent, pk.ent).isEquals();

	    public int hashCode() {
	    	return new HashCodeBuilder().append(pk1).append(ent).toHashCode(); 




Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s