views:

334

answers:

2

I'm having a major problem getting a parent/child relationship working for a hierarchy of a single class. Basically I have to represent a server tree like thus:

Server A
    Server B
        Server C
        Server D
    Server E
        Server C
        Server D
    Server F
    Server G

Note that the children of Servers B & E are the same. My original mapping was something like this, which was fine until I needed to have the objects for server C & D being the same instance, so having a single column for PARENT_ID got filled by the last relationship and only one of servers B or E would show the children:

<hibernate-mapping ...>
  <class name="Server" ...>
    ...
    <set name="children" cascade="all-delete-orphan" lazy="false">
      <key column="PARENT_ID" />
      <one-to-many class="Server" />
    </set>
  </class>
</hibernate-mapping>

I know I need to do some sort of cross reference table to map the fact that a server can have multiple parents, but all the examples I've found on-line contain a separate parent and child class.

Can anyone tell me how to do a cross reference parent/child mapping for the same class...? I.e. something like:

<hibernate-mapping ...>
  <class name="Server" ...>
    ...
    <set name="children" cascade="all-delete-orphan" lazy="false">
      <key>
        <column name="PARENT_ID" />
        <column name="CHILD_ID" />
      </key>
      <many-to-many class="Server">
        <column name="???" />
        <formula>???</formula>
      </many-to-many>
    </set>
  </class>
</hibernate-mapping>

Thanks,

Bob.

+1  A: 

In your many-to-many mapping, set the column name to be CHILD_ID.

<many-to-many class="Server">
     <column name="CHILD_ID" />
</many-to-many>

This will cause the relationship to view the child id as the id representing itself. While the one-to-many relationship will use the parent_id as the id representing itself. Should work, I haven't ran it, but I have done a similar thing before.

Zoidberg
That appears to have done the trick, thanks.Bob.
fatboab
A: 

Doing the following:

...
<set name="children" table="SERVER_XREF" cascade="all-delete-orphan" lazy="false">
  <key column="PARENT_ID" />
  <many-to-many class="Server" column="CHILD_ID" />
</set>
...

appears to have resulted in the server hierarchy I was after being returned.

Cheers,

fatboab