First off I am a hibernate noob and apologize for my ignorance. I have a User object which contains a set of parents (which are user objects) and children (which are user objects) The mapping is handled in a mapping table. it looks like this
Code:
mysql> desc user_relationship;
+-----------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+---------+------+-----+---------+-------+
| parent_id | int(11) | NO | PRI | | |
| user_id | int(11) | NO | PRI | | |
+-----------+---------+------+-----+---------+-------+
I am mapping users to parents and children using the following mapping:
Code:
<hibernate-mapping>
<class name="User" table="user">
<id name="id" type="int">
<generator class="identity"/>
</id>
<property name="username" column="username" type="java.lang.String"/>
<set name="children" table="user_relationship">
<key column="parent_id"/>
<many-to-many column="user_id" class="User"/>
</set>
<set name="parents" table="user_relationship" >
<key column="user_id"/>
<many-to-many column="parent_id" class="User"/>
</set>
</class>
</hibernate-mapping>
A problem arises when I try to save the users and their relationships to the DB. If userA is a parent of userB, hibernate attempts to insert the relationship between userA and userB which succeeds, then it tries to insert the relationship between userB and userA which obviously fails, because its the same relationship resulting in a unique constraint violation. I think I can get around it by never saving the child relationships. Without using annotations, is there a way I can make the children collection read only? If not, is there a better design that would accomplish this? I'm sure the whole recursive mapping using lookup tables has been done before somewhere.
Thanks