I have a situation where a class has a primary key consisting of two foreign key references.
Heres the code for the class:
Code:
@Entity
@IdClass(MembershipPK.class)
public class Membership {
protected Membership() {
// Needed for JPA
}
public Membership(User user, Group group) {
this.group = group;
this.user = user;
}
@Id
@ManyToOne
Group group;
@Id
@ManyToOne
User user;
public Group getGroup() {
return group;
}
public User getUser() {
return user;
}
}
And here is the code for the primary key:
Code:
@Embeddable
public class MembershipPK implements Serializable {
@ManyToOne(fetch=FetchType.EAGER)
@JoinColumn(referencedColumnName="id", nullable=false, insertable=false, updatable=false)
public Group group;
@ManyToOne(fetch=FetchType.EAGER)
@JoinColumn(referencedColumnName="id", nullable=false, insertable=false, updatable=false)
public User user;
public MembershipPK() {}
public MembershipPK(User user, Group group) {
this.user = user;
this.group = group;
}
@Override
public boolean equals(Object obj) {
if(!(obj instanceof MembershipPK)) {
return false;
}
MembershipPK other = (MembershipPK) obj;
return group.getId() == other.group.getId() && user.getId() == other.user.getId();
}
@Override
public int hashCode() {
return group.getId() * 3 + user.getId();
}
}
This seems to be more or less what you want to do, so maybe you can use a similar approach.