Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to handle bidirectional relationships when constructing hibernate entities?
    text
    copied!<p>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 <code>Account</code> and <code>Group</code> like</p> <pre><code>public class Account { private List&lt;Group&gt; groups = new ArrayList&lt;Group&gt;(); public Account() {} public void setGroups(List&lt;Group&gt; usergroups) { this.groups = groups; } @OneToMany(mappedBy = "account") public List&lt;Group&gt; getGroups() { return groups; } } </code></pre> <p>and</p> <pre><code>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&lt;Group&gt; accountGroups = account.getGroups(); accountGroups.add(this); } @ManyToOne public Account getAccount() { return account; } public void setAccount(Account account) { this.account = account; } } </code></pre> <p>My question is now about the usage of the helper method <code>addToAccount</code> in the constructor of <code>Group</code>. 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.</p> <p>However I believe calling the method <code>addToAccount</code> in the constructor is not a good idea, because</p> <ol> <li><p>The <code>List</code> of <code>Group</code>s is lazily fetched, so calling the method <code>addToAccount</code> needs an open transaction. So the constructor of <code>Group</code> can only be called inside an open transaction. In my opinion this is a very annoying restriction.</p></li> <li><p>The <code>Account</code> object given as argument to the constructor of <code>Group</code> is changed by the constructor. In my opinion, this is an surprising side effect of the <code>Group</code> constructor and should not happen.</p></li> </ol> <p>My suggestion was to better use a simple constructor like</p> <pre><code> public Group(String name, Account account) { this.name = name; this.account = account; } </code></pre> <p>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?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload