title: Hibernate - clearing a collection with all-delete-orphan and then adding to it causes ConstraintViolationException
body: <p>I have these entities</p>
  
  <pre><code>class Foo{
      Set&lt;Bar&gt; bars;
  }
  
  class Bar{
      Foo parent;
      String localIdentifier;
  }
  </code></pre>
  
  <p>With this mapping (sorry, no annotations, I'm old fashioned):</p>
  
  <pre><code>&lt;class name="Foo"&gt;
      ...
      &lt;set name="bars" cascade="all-delete-orphan" lazy="false" inverse="true"&gt;
          &lt;key&gt;...&lt;/key&gt;
          &lt;one-to-many class="Bar"/&gt;
      &lt;/set&gt;
  &lt;/class&gt;
  
  
  &lt;class name="Bar"&gt;
      ...
      &lt;property name="localIdentifier" column="local_identifier"/&gt;
      &lt;many-to-one name="parent" column="parent_id" /&gt;
  &lt;/class&gt;
  </code></pre>
  
  <p>I also have a unique constraint on 2 columns: <code>local_identifier</code> and <code>parent_id</code> (not a unique constrain on each, but a single unique constrain containing both, e.g. no 2 rows with the same parent and same localIdentifier are allowed)</p>
  
  <pre><code>alter table bar add constraint unique_bar unique (parent_id, local_identifier)
  </code></pre>
  
  <p>And this code that uses them:</p>
  
  <pre><code>//foo is persistent, foo id = 1
  Bars bars = foo.getBars();
  bars.clear(); // bars contained 1 item [parent_id = 1, local_identifier = "a"]
  Bar newBar = new Bar();
  newBar.setParent(foo);
  newBar.setLocalIdentifier("a");
  bars.add(newBar);
  </code></pre>
  
  <p>Now, for some reason, Hibernate doesn't execute things in the order they were called. It doesn't execute the <code>clear()</code> (delete) before the <code>add()</code> (insert) but vice versa, it first tries to insert, getting a <code>ConstraintViolationException</code></p>
  
  <p>I know adding a little <code>session.flush()</code> after <code>bars.clear();</code> , could fix this, but in this case, I have no access to the session in a non ugly way.</p>
  
  <p>So is flush is the only solution? or is there a Hibernate version that respects the order of actions?</p>
  
  <p><strong>Update:</strong>
  By the way, dereferencing the collection will result in a HibernateException from <a href="https://www.hibernate.org/117.html#A3" rel="noreferrer">https://www.hibernate.org/117.html#A3</a>: </p>
  
  <blockquote>
    <p><b>I get HibernateException: Don't
    dereference a collection with
    cascade="all-delete-orphan"</b> This
    will happen if you load an object with
    a cascade="all-delete-orphan"
    collection and then remove the
    reference to the collection. Don't
    replace this collection, use clear()
    so the orphan-deletion algorithm can
    detect your change.</p>
  </blockquote>