WikiBooks has a great page,
Java Persistence/Identity and Sequencing that covers defining an Id for a OneToOne or ManyToOne in JPA 2.0. Works great. But the relationship is uni-directional. Is it possible to make it bi-directional?
It would be really useful to call Employee.phones.
Code:
@Entity
@IdClass(PhonePK.class)
public class Phone {
@Id
private String type;
@ManyToOne
@Id
@JoinColumn(name="OWNER_ID", referencedColumnName="EMP_ID")
private Employee owner;
...
}
Code:
public class PhonePK {
private String type;
private long owner;
public PhonePK() {}
public PhonePK(String type, long owner) {
this.type = type;
this.owner = owner;
}
public boolean equals(Object object) {
if (object instanceof PhonePK) {
PhonePK pk = (PhonePK)object;
return type.equals(pk.type) && owner == pk.owner;
} else {
return false;
}
}
public int hashCode() {
return type.hashCode() + owner;
}
}
Code:
@Entity
public class Employee {
@Id
@Column(name = "EMP_ID")
private Integer id;
private String firstName;
private String lastName;
@OneToMany(mappedBy="owner")
private List<Phone> phones;
...
}
Thanks for your help.
UPDATE: This appears to work. Not sure what my issue was.