Hibernate version: 2.1.6
Database: MySql
Simple parent-and-children relationship. One category can have several subcategories. For example, Category "Computers" has two subcategories named "Monitors" and "DesktopPCs".
Code:
-------------
| Computers |
-------------
|
----------------------------
| |
------------- --------------
| Monitors | | DesktopPCs |
------------- --------------
When I fetch "Computers" from database and list its subcategories, it works well, but if I navigate from "Monitors" to "Computers" then Nagivate back, it doesn't. Is it a bug or something.
Code:
private static void retrieve() {
Category root = null;
String name = "Monitors";
Session sess = HibernateUtil.getSession();
try {
HibernateUtil.beginTransaction();
Query q = sess.createQuery("from Category c where c.name = :name");
q.setString("name", name);
root = (Category)q.list().get(0);
//Navigate to "Computers"
System.out.println(root.getParentCategory().getName());
//Navigate back to every child, fail
Iterator iter = root.getParentCategory().getChildCategories().iterator();
while(iter.hasNext())
System.out.println(((Category)iter.next()).getName());
HibernateUtil.commitTransaction();
} catch(InfrastructureException e) {
HibernateUtil.rollbackTransaction();
} catch(HibernateException e) {
HibernateUtil.rollbackTransaction();
} finally {
HibernateUtil.closeSession();
}
}
Part of output in console:
Quote:
Hibernate: select category0_.CATEGORY_ID as CATEGORY1_, category0_.NAME as NAME, category0_.PARENT_CATEGORY_ID as PARENT_C3_ from OA_CATEGORY category0_ where (category0_.NAME=? )
Hibernate: select category0_.CATEGORY_ID as CATEGORY1_0_, category0_.NAME as NAME0_, category0_.PARENT_CATEGORY_ID as PARENT_C3_0_ from OA_CATEGORY category0_ where category0_.CATEGORY_ID=?
Computers
Category.hbm.xml
Code:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 2.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">
<hibernate-mapping
>
<class
name="model.Category"
lazy="true"
>
<id
name="id"
column="CATEGORY_ID"
type="java.lang.Long"
>
<generator class="native">
</generator>
</id>
<property
name="name"
type="java.lang.String"
update="true"
insert="true"
column="name"
/>
<key
column="fk_Category"
>
</key>
<many-to-many
class="model.Item"
column="fk_Item"
outer-join="auto"
/>
</set>
<set
name="childCategories"
lazy="true"
inverse="true"
cascade="save-update"
batch-size="10"
sort="unsorted"
>
<key
column="PARENT_CATEGORY_ID"
>
</key>
<one-to-many
class="model.Category"
/>
</set>
<many-to-one
name="parentCategory"
outer-join="false"
class="model.Category"
cascade="none"
update="true"
insert="true"
column="PARENT_CATEGORY_ID"
/>
</class>
</hibernate-mapping>