title: Hibernate: How to properly map Sets with Composite Element containing a Many-to-one?
body: <p>I have a mapping similar to the following:</p>
  
  <pre><code>&lt;set name="tracks" table="tracks"&gt;
      &lt;key column="album_id" /&gt;
      &lt;composite-element class="Track"&gt;
  
          &lt;many-to-one name="song" column="song_id" class="Song" cascade="none" /&gt;
  
          &lt;property name="trackNumber" column="track_number" type="java.lang.Integer" not-null="false"/&gt;
      &lt;/composite-element&gt;
  &lt;/set&gt;
  </code></pre>
  
  <p>Generally with mappings similar to this, I've noticed that when saving the parent entity, Hibernate likes to delete all the elements of the collection first, before adding back the new elements. I've already come to accept this as standard behaviour.</p>
  
  <p>However, with the mapping file I've given above, I run into an error that seems two fold.</p>
  
  <p>First, Hibernate appears to be trying to delete the elements of the collection by issuing a DELETE statement using <strong>every column</strong> on the track table. Secondly, this still fails whenever trackNumber is null, since the DELETE statement includes a</p>
  
  <pre><code>DELETE FROM track WHERE album_id = ? AND song_id = ? AND track_number = ?
  </code></pre>
  
  <p>Which doesn't delete the track at all. It should really be doing for null, a</p>
  
  <pre><code>DELETE FROM track WHERE album_id = ? AND song_id = ? AND track_number is ?
  </code></pre>
  
  <p><strong>Either way, what I'd <em>really</em> like is something simple like</strong></p>
  
  <pre><code>DELETE FROM track WHERE album_id = ?
  </code></pre>
  
  <p>This seems to work when I replace the many-to-one mapping with simply the song_id</p>
  
  <pre><code>&lt;set name="tracks" table="tracks"&gt;
      &lt;key column="album_id" /&gt;
      &lt;composite-element class="Track"&gt;
  
          &lt;property name="songId" column="song_id" type="int" /&gt;
  
          &lt;property name="trackNumber" column="track_number" type="java.lang.Integer" not-null="false"/&gt;
      &lt;/composite-element&gt;
  &lt;/set&gt;
  </code></pre>
  
  <p>But I need the track data too... any help?</p>
  
  <p>Edit:</p>
  
  <p>Maybe I should clarify my question.</p>
  
  <p>How do I make it so my deletes on this set do not rely on trackNumber?</p>