title: Hibernate: @OrderBy vs @OrderColumn to maintain the order of a collection
body: <p>What is the preferred way for maintaining the order of a collection while persisting and also while retrieving from database?</p>
  
  <p>I know that @OrderBy is more of a in-memory sorting that might work in retrieving only when you presist the rows in the order of column you chose.</p>
  
  <p>Let's say I chose to use a column backed by a database sequence, will hibernate make sure that  elements in collection are persisted in the same order as in collection (say List).</p>
  
  <p>Any thought?</p>
  
  <h2>More details:</h2>
  
  <p>Let’s say I have a class A which has one-to-many relationship with class B. B has a primary key field, ‘Id’, which is backed by a sequence in DB. </p>
  
  <pre><code>Class A {
    List&lt;B&gt; bList;
  }
  </code></pre>
  
  <p>I always wanted to retain the order of elements B in A like below:</p>
  
  <pre><code>bList = { b1, b2, b3 }
  </code></pre>
  
  <p>One way to achieve is using @OrderBy (“Id ASC”). This would work only when the list B is persisted in the order as below:</p>
  
  <pre><code>----------------
  Id ----bValue
  ----------------
  
  1------ b1
  2------ b2
  3-------b3
  ------------------
  </code></pre>
  
  <p>When we retrieve since it is ordered by Id, the order is maintained.</p>
  
  <p>Let’say the collection B is persisted in the following way:</p>
  
  <pre><code>----------------
  Id ----bValue
  ----------------
  1------ b2
  2------ b1
  3-------b3
  ------------------
  </code></pre>
  
  <p>When we retrieve, the order of list B go for a toss (since it is order by Id column). So my question, if the collection B always persist in the same order as it appears in the list or not.</p>