Search code examples
hibernatehbm

Recursive HBM Mapping


Can I do the following in my HBM mapping?

<class name="Employee" table="employees">
    <!-- assume that each person only has exactly one supervisor -->
    <many-to-one name="supervisor" class="Employee" column="supervisorId" />
</class>

When I use the above HBM mapping, my server refuses to start with the following error:

org.hibernate.InstantiationException: could not instantiate test object Employee
Caused by: java.lang.StackOverflowError
at Employee.<init>(Employee.java:11)
at Employee.<init>(Employee.java:11)
at Employee.<init>(Employee.java:11)
...... (about a hundred duplicates)

line 11 of Employee.java merely says:

public class Employee implements Serializable {

How should I model my supervisor-employee relationship? There is no special POJO for supervisor and supervisor objects have no special fields.


Solution

  • Hibernate shouldn't have a problem with mapping such a relationship.

    It looks like infinite recursion is caused by error in your code, something like this:

    public class Employee {
        private Employee supervisor = new Employee();
    }