Note that there are some explanatory texts on larger screens.

plurals
  1. POProblem with equals() method in Hibernate
    primarykey
    data
    text
    <p>I am developing an application in Hibernate where I have model classes like these:</p> <pre><code>public class Employee { private int ID; private String name; private Department department; //other properties //constructors, getters and setters } </code></pre> <p>Note that the <code>ID</code> is not a value populated by the user and is populated using <code>GenerationType.Identity</code> as the <code>strategy</code>.</p> <p>Also I have another class <code>Department</code> as follows:</p> <pre><code>public class Department { private int ID; private String name; private Set&lt;Employee&gt; employees; //this is actually a HashSet //other implementations } </code></pre> <p>There is a <code>ManyToOne</code> bi-directional relationship between an <code>Employee</code> and a <code>Department</code>.</p> <p>So to add a new <code>Employee</code> to an existing <code>Department</code>, I do the following</p> <pre><code>Department existingDepartment = ...; Employee newEmployee = ...; existingDepartment.addEmployee(newEmployee); employee.setDepartent(existinDepartment); session.save(newEmployee); </code></pre> <p>Now conceptually two <code>Employee</code> objects are the same if they have the same <code>ID</code>. So my <code>equals()</code> method in the <code>Employee</code> class looks like this:</p> <pre><code>public boolean equals(Object o) { if(!(o instanceOf Employee)) { return false; } Employee other = (Employee)o; if(this.ID == o.etID()) { return true; } return false; } </code></pre> <p>Now the problem is when I create a <code>new Employee();</code> I do not have its <code>ID</code>, since it will be assigned when it will be persisted. So when I say </p> <pre><code>existingDepartment.addEmployee(newEmployee); </code></pre> <p>the internal <code>HashSet</code> of the <code>Department</code> object is effectively using an <code>equals()</code> method which is broken [since it uses a member variable to determine equality that as not been initialized properly].</p> <p>This seems like a very basic problem but, how do I solve it? Or am I designing my classes totally wrong? Or should my <code>equals</code> method be re-written to compare other values instead of <code>ID</code>, which I guess would be absurd.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload