title: JPA OneToMany : List vs Set
body: <p>I have two entities: <code>UserAccount</code> and <code>Notification</code>. These have a relationship as shown below.</p>
  
  <pre><code> public class UserAccount {
  
      @Id
      @Column(name = "USER_NAME")
      private String emailId;
  
      @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
      @JoinTable(name = "USERS_NOTIFICATIONS", joinColumns = { @JoinColumn(name = "USER_NAME") }, inverseJoinColumns = { @JoinColumn(name = "NOTIFICATION_ID") })
      private List&lt;Notification&gt; notifications;
  
      //setters, getter, equals and hashcode
   }
  </code></pre>
  
  <p>Both <code>equals()</code> and <code>hashcode()</code> are overridden (generated by the IDE with business key/primary key).</p>
  
  <p>Given a <code>UserAccount</code>, when I add the first <code>Notification</code>, it results in an INSERT statement. But on further addition for the same <code>UserAccount</code>, it first deletes and then inserts:</p>
  
  <pre><code>Hibernate: delete from USERS_NOTIFICATIONS where USER_NAME=?
  Hibernate: insert into USERS_NOTIFICATIONS (USER_NAME, NOTIFICATION_ID) values (?, ?)
  Hibernate: insert into USERS_NOTIFICATIONS (USER_NAME, NOTIFICATION_ID) values (?, ?)
  Hibernate: insert into USERS_NOTIFICATIONS (USER_NAME, NOTIFICATION_ID) values (?, ?)
  //as many inserts as the notifications the user has
  </code></pre>
  
  <p>The same happens with every <code>UserAccount</code>. If I replace the <code>List</code> with <code>Set</code>, a normal INSERT occurs. I found the reason after reading this <a href="http://docs.jboss.org/hibernate/orm/4.1/manual/en-US/html/ch20.html#performance-collections-mostefficientupdate" rel="noreferrer">documentation</a> and a <a href="http://assarconsulting.blogspot.in/2009/08/why-hibernate-does-delete-all-then-re.html" rel="noreferrer">blog</a>. </p>
  
  <p><strong>Observations from docs</strong></p>
  
  <ul>
  <li>In a unidirectional <code>@OneToMany</code> association, <code>Set</code> is preferred.</li>
  </ul>
  
  <blockquote>
    <p>It should be clear that indexed <code>Collections</code> and <code>Sets</code> allow the most efficient operations in terms of adding, removing and updating elements.</p>
  </blockquote>
  
  <ul>
  <li>In a bidirectional <code>@OneToMany</code> relationship (<code>@ManyToOne</code> managing), <code>List</code> and <code>Bags</code> are efficient.</li>
  </ul>
  
  <blockquote>
    <p><code>Bags</code> and <code>Lists</code> are the most efficient inverse <code>Collections</code>.</p>
  </blockquote>
  
  <hr>
  
  <p>Having said that, which is more preferable:</p>
  
  <ol>
  <li><p>A <code>Set</code> over a <code>List</code> in a unidirectional <code>@OneToMany</code> mapping?</p></li>
  <li><p>Or, do I have to tweak my domain model by adding a bidirectional relationship to use a <code>List</code>, especially when there are duplicates?</p></li>
  </ol>