What's the correct way to code a one-to-one bidirectional relationship in a POJO?
Something like this perhaps, but you end up with mutual recursion:
User.java
public void setAddress(Address address) {
this.address = address;
address.setUser(this);
}
Address.java
public void setUser(User user) {
this.user = user;
user.setAddress(this);
}
I suppose you could access the member variables directly, but that breaks encapsulation. Or should you avoid this type of relationship, since Users and Addresses both knowing about each other limits re-use?
(Sorry if this is a FAQ; I couldn't find anything by searching or in Hibernate In Action. Should CaveatEmptor include an example of this type of relationship? Bid<>Item is almost there.)
|