title: How to use the insertion order of a LinkedHashSet in @OneToMany
body: <p>What I have is an application that have many events. These events are in chronological order but all I get is a JSON array of eventCodes so the array order is the order in which they were added. </p>
  
  <p>It seems hibernate prefers <code>Set</code>s over <code>List</code>s from what I can find on google and SO however using a <code>Set</code> I need to maintain order of the entries for which I have chosen to use <code>LinkedHashSet</code> because it maintains insertion order (based on plenty of SO questions). </p>
  
  <p>Which is where my issue is. I have set an <code>OrderBy</code> on sequence of an applicationEvent which is the index of the JSON array for that object (insertion into the DB seems random so using Id did not work). Looking at the hibernate generated SQL it seems to be getting what I expect. All the event in order of Sequence 1-n. </p>
  
  <p>However when I loop to build a list the order seems to be random not respecting what I perceive as the appropriate insertion order.</p>
  
  <pre><code>Iterator&lt;ApplicationEventDTO&gt; iter = applicationEvents.iterator();
  List&lt;ApplicationEventDTO&gt; list = new ArrayList&lt;ApplicationEventDTO&gt;();
  while(iter.hasNext()){
      list.add((ApplicationEventDTO) iter.next());
  }
  </code></pre>
  
  <p>Application Entity:</p>
  
  <pre><code>@Entity
  @Table
  public class Application {
  //Lots of other stuff
      private Set&lt;ApplicationEvent&gt; applicationEvents=new LinkedHashSet&lt;ApplicationEvent&gt;();
  
      @OneToMany (mappedBy = "application", fetch = FetchType.EAGER
      , cascade=CascadeType.ALL, orphanRemoval=true)
      @NotAudited
      @OrderBy("sequence")
      public Set&lt;ApplicationEvent&gt; getApplicationEvents() {
          return applicationEvents;
      }
  
      public void setApplicationEvents(Set&lt;ApplicationEvent&gt; applicationEvents) {
          this.applicationEvents = applicationEvents;
      }
  }
  </code></pre>
  
  <p><strong>Update</strong></p>
  
  <p>To add a bit more information it was the below articles that lead me to stick with Sets over Lists. </p>
  
  <p><a href="https://vladmihalcea.com/hibernate-facts-favoring-sets-vs-bags/" rel="nofollow noreferrer">https://vladmihalcea.com/hibernate-facts-favoring-sets-vs-bags/</a></p>
  
  <p><a href="https://stackoverflow.com/questions/4334970/hibernate-cannot-simultaneously-fetch-multiple-bags">Hibernate cannot simultaneously fetch multiple bags</a> -- A comment at the end suggest that Sets are preferable over Lists.</p>
  
  <p>The Application Entity is very large and has many relationships. All of which appear to be Sets. When Attempting to change Events to a List I receive: <code>cannot simultaneously fetch multiple bags</code> which is how I found the SO question.</p>