title: Why does Hibernate try to delete when I try to update/insert?
body: <p>In my app I have these Hibernate-mapped types (general case):</p>
  
  <pre><code>class RoleRule {
    private Role role;
    private PermissionAwareEntity entity; // hibernate-mapped entity for which permission is granted
    private PermissionType permissionType; // enum
  
    @ManyToOne
    @JoinColumn(name = "ROLE_ID")
    public Role getRole() {
      return role;
    }
    public void setRole(Role role) {
      this.role = role;
    }
  
  }
  
  class Role {
    private Set&lt;RoleRule&gt; rules = new HashSet&lt;RoleRule&gt;(0);
  
    @OneToMany(cascade=CascadeType.ALL)
    @JoinColumn(name="ROLE_ID")
    public Set&lt;RoleRule&gt; getRules() {
      return rules;
    }
    public void setRules(Set&lt;RoleRule&gt; rules) {
      this.rules = rules;
    }
  
  }
  </code></pre>
  
  <p>All classes have <code>equals() &amp; hashCode()</code> overrides.</p>
  
  <p>My application allows tweaking of roles (by sysadmins only, don't worry), and among other fields, allows creation of new role rules. When a new rule is created I try to create a new <code>RoleRule</code> object and insert it into the role's field <code>rules</code>. I call <code>session.update(role)</code> to apply the changes to the database.</p>
  
  <p>Now comes the ugly part... Hibernate decides to do the following when closing the transaction and flushing:</p>
  
  <ol>
  <li>Insert the new rule into the database. Excellent.</li>
  <li>Update the other role fields (not collections). So far so good.</li>
  <li>Update the existing rules, even if nothing has changed in them. I can live with this.</li>
  <li>Update the existing rules <em>again</em>. Here's a paste from the log, including the automatic comment:<br></li>
  </ol>
  
  <pre>/* delete one-to-many row Role.rules */
  update ROLE_RULE set ROLE_ID=null where ROLE_ID=? and ROLE_RULE_ID=?</pre>
  
  <p>Of course, all fields are not-null, and this operation fails spectacularly.</p>
  
  <p>Can anyone try to explain why Hibernate would do this??? And even more important, how the frak do I get around this???</p>
  
  <p><strong>EDIT</strong>: I was so sure it was something to do with the mapping, and then my boss, on a whim, deleted the <code>equals()</code> and <code>hashCode()</code> in both classes, recreated them using Eclipse, and mysteriously this solved the problem.</p>
  
  <p>I'm still very curious about my question though. Can anyone suggest why Hibernate would do this?</p>