I want to model the relationship between two entities, a group and an account with JPA/Hibernate. An account can have several groups, but not vice versa, so we have a OneToMany relationship between account and group.
My working colleague suggested to model the entities Account
and Group
like
public class Account {
private List<Group> groups = new ArrayList<Group>();
public Account() {}
public void setGroups(List<Group> usergroups) {
this.groups = groups;
}
@OneToMany(mappedBy = "account")
public List<Group> getGroups() {
return groups;
}
}
and
public class Group {
private String name;
private Account account;
public Group() {}
public Group(String name, Account account) {
this.name = name;
addToAccount(account);
}
public void addToAccount(Account account) {
setAccount(account);
List<Group> accountGroups = account.getGroups();
accountGroups.add(this);
}
@ManyToOne
public Account getAccount() {
return account;
}
public void setAccount(Account account) {
this.account = account;
}
}
My question is now about the usage of the helper method addToAccount
in the constructor of Group
. According to my working colleague this method is necessary because we need to update the bidirectional relationship between the two entities from both sides to ensure a consistent memory model of the two entities.
However I believe calling the method addToAccount
in the constructor is not a good idea, because
The
List
ofGroup
s is lazily fetched, so calling the methodaddToAccount
needs an open transaction. So the constructor ofGroup
can only be called inside an open transaction. In my opinion this is a very annoying restriction.The
Account
object given as argument to the constructor ofGroup
is changed by the constructor. In my opinion, this is an surprising side effect of theGroup
constructor and should not happen.
My suggestion was to better use a simple constructor like
public Group(String name, Account account) {
this.name = name;
this.account = account;
}
and deal with the bidirectional relationship manually. But maybe I'm wrong. Is there a common way how one should handle bidirectional relationships when constructing hibernate entities?