OK. Hopefully this will help:
I have only one entity in my data base, person. Here is the mapping for Person.
Code:
<class name="com.orkut.Person" table="PERSON">
<meta attribute="class-description">
Represents a single Person in the Orkut Database.
@author RMH
</meta>
<id name="id" type="int" column="PERSON_ID">
<meta attribute="scope-set">protected</meta>
<generator class="native"/>
</id>
<property name="firstName" type="string" not-null="true"/>
<property name="lastName" type="string" not-null="true"/>
<set name="friends" table="FRIENDS_LINK" >
<key column="person_1_id"/>
<many-to-many class="com.orkut.Person" column="person_2_id"/>
</set>
</class>
The class generated from this looks like this:Code:
package com.orkut;
import java.io.Serializable;
import java.util.Set;
import org.apache.commons.lang.builder.ToStringBuilder;
/**
* Represents a single Person in the Orkut Database.
* @author RMH
*
*/
public class Person implements Serializable {
/** identifier field */
private Integer id;
...
/** persistent field */
private Set friends;
...
public Set getFriends() {
return this.friends;
}
public void setFriends(Set friends) {
this.friends = friends;
}
...
}
I run one script to populate my database. Its very simple and it worksCode:
tx = session.beginTransaction();
Person rrose = new Person("Richard","Rose",new java.util.HashSet());
session.save(rrose);
Person dWater = new Person("David","Water",new java.util.HashSet());
session.save(dWater);
Person dSteel = new Person("David","Steel",new java.util.HashSet());
session.save(dSteel);
Person dWood = new Person("Don","Wood",new java.util.HashSet());
session.save(dWood);
rrose.getFriends().add(dWater);
rrose.getFriends().add(dSteel);
rrose.getFriends().add(dWood);
dWater.getFriends().add(dSteel);
dSteel.getFriends().add(dWood);
// We're done; make our changes permanent
tx.commit();
I than run a script to query the database. Its also simple:Code:
for (Iterator iter = session.find("from com.orkut.Person").iterator() ; iter.hasNext() ; ) {
Person person = (Person)iter.next();
outName(person.getFirstName()+" "+person.getLastName());
for(Iterator friends = person.getFriends().iterator();friends.hasNext(); ){
Person friend = (Person)friends.next();
outName(" "+friend.getFirstName()+" "+friend.getLastName());
}
}
The output from this query is as follows:Code:
qtest:
[java] Richard Rose
[java] David Steel
[java] David Water
[java] Don Wood
[java] David Water
[java] David Steel
[java] David Steel
[java] Don Wood
[java] Don Wood
However, if the relationship was bidirectional than it should have looked like this (bold items were missing):Code:
qtest:
[java] Richard Rose
[java] David Steel
[java] David Water
[java] Don Wood
[java] David Water
[java] David Steel
[java] Richard Rose
[java] David Steel
[java] Don Wood
[java] Richard Rose
[java] Don Wood
[java] David Steel
[java] Richard Rose