Reza Ghafari

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.

[sourcecode language=“css”]

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

@Id PK id;

//other fields @Embeddable public static class PK implements Serializable{ public PK (){} @Column (name=“PK_1”) private Long pk1; @ManyToOne(fetch=FetchType.EAGER,optional=false) @JoinColumn(name=“PK_2”) 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(); }

//getter/setter }

//getter/setter

} [/sourcecode]