Hey all, i am very new to hibernate so please bear with me. I have a case where lets say I have a person object, very generic. In the person object, there is an id (number), name (map to varchar), age (map to number), blah, blah, then a parent variable that is another Person object. So each Person class has a parent attribute which is a Person object. Lets say in my db, i have 2 tables. 1 called people, 2nd called parents. In the parents table i have only two columns, 1 for parent_id and 2nd for child_id. They both map to the People table using the person_id. How the heck to I map this using hibernate? Please help!!!
Ok, but now what if all these parent child relationships are in a tree, like a family tree. The amount of levels is 0 to whatever, lets say 4 levels. Now we have great grand parents who have children, grand parents who have a parent and children, parents who have grand parents and children, and children with parent but no children. Currenly the children aspect works by using a list attribute. Will the many-to-one still work given the scenario? Thanks a ton.
The normal way to map a tree in a relational database is in one table. Your Parents are also Persons, so I'd suggest Parent is a property of Person (of the type Person) rather than a distinct object itself. Add two fields to your Person table: father and mother, then add one-to-many relationships to this table with itself, where father and mother are the FKs. That way you can support an ancestry to the nth level, rather than one 1 level. Make sense? [ December 12, 2005: Message edited by: Paul Sturrock ]
The normal way to map a tree in a relational database is in one table.
Mapping the relationship in a separate table is more generic. You can add additional relationships (step-father, step-mother, godparents, etc.) without adding additional columns to the Person table. Some of the relationships could be one-to-many (marriages!) If you had to add a new column for every possible type of relationship it could get out of hand.
Also, you can add attributes to the relationship entity like relationship type, estranged=[true|false] or even effective/expiration dates (ouch! Somebody got disowned!).
Hibernate In Action section 6.3 has a discussion on mapping associations with several examples. If you don't have a copy handy, you can try chapter 8 of the Hibernate manual.
If you have an existing database schema, you can use Middlegen to reverse engineer the schema into a basic mapping file that you can tweak as necessary. This is most helpful when you have a complex, pre-existing schema.