Hibernate Does Not Handle Self Referencing Tables Well
After much searching around the Internet I have come to the conclusion that Hibernate really doesn’t support self-referencing tables. The typical example is something like this table:
Table Category
---------------
categoryId int
name varchar(50)
parent int
In this example the Hibernate code would be something like:
Category parent = ...Category child = ...
child.setParent(parent)
dao.create(child);//this does not appear to actually do anything in a self-referencing table
parent.getChildren().add(child);
dao.saveOrUpdate(parent);session.flush();
//and then later on
Category category = categoryDao.something();
for(Category child:category.getChildren()) {
//do something with each child
}
Notes:
- Since the reference is in the same table, the above add() to the parent children does nothing.
- The setParent() call is just setting the parent column directly in the Category object – no database action is taking place.
- Calls to getChildren() are doing a simple query unlike other getObject ORM calls in Hibernate
- Calls to getParent() are also doing abnormal ORM calls
All of the above code ‘works’. It just doesn’t work like anything else really in Hibernate.
