Hi,
there are four missed points in your configuration
1- i think you cannot use same primary key as foreign key in your scenario
2- bag should have cascade attribute with value save-update or all-delete-orphan
3- you have to add many-to-one relation to the parent "cat"
4- its recommended in such case to set true to attribute inverse
configuration file will be
Code:
<class name="my.Cat" table="cat" lazy="true">
<id name="catId" column="cat_id"
type="long">
<generator class="hilo">
<param name="max_lo">100</param>
</generator>
</id>
<property name="name" length="100" column="name" />
<bag name="cats" inverse="true" cascade="all-delete-orphan" >
<key column="parent_cat_id" />
<one-to-many
class="my.Cat" />
</bag>
<many-to-one name="parentCat" class="my.Cat"
column="parent_cat_id" />
</class>
don't forget to add get/set of parentCat and set the parent before save
for example:
Code:
Session session = sessions.openSession();
Transaction tx = session.beginTransaction();
Cat c = new Cat();
Collection<Cat> cats = new ArrayList<Cat>(5);
for (int i = 0; i < 5; i++) {
Cat c1 = new Cat();
//set the parent CAT
c1.setParentCat(c);
cats.add(c1);
}
c.setCats(cats);
Serializable obj = session.save(c);
System.out.println(obj);
tx.commit();
session.close();
finally, it's better in Cat class to use Collection than List and in this scenario it is better to use set instance of bag
Mahmoud