Hibernate: Specifying columns in a one-to-many relationship
database, hibernate, java, schema
Solution
Try something like this in the parent:
<set name="childs" inverse="true" lazy="true" table="child" fetch="select">
<key column="child_parent_code" property-ref="code" />
<one-to-many class="foo.bar.Child" />
</set>
and this in the child:
<many-to-one name="parent" class="foo.bar.Parent"
fetch="select" column="child_parent_code" property-ref="code" />
I have assumed that the code property in the parent is called "code".
Problem
I'm trying to build a Hibernate layer for a database schema I have essentially no control over. Simplified, there are two tables. Table `parent` has two important columns: - `parent_id`, integer, primary key, autoincremented - `parent_code`, string, unique key, generated by a black box somewhere (let's say this is a UUID for sanity's sake) - Plus a bunch of columns of data Table `child` has two important columns: - `child_parent_id`, integer, primary key, autoincremented - `child_parent_code`, string, foreign key pointing at the parent's `parent_code` value - Plus a bunch of columns of data I want to be able to call Parent.getChilds() and get a Collection of Child objects. But setting up the Hibernate mapping files seems impossible. What it's doing with the mappings below is searching the `child` table with the `parent_id` value (instead of `parent_code`). In `Parent.hbm.xml`: ``` <set name="childs" inverse="true" lazy="true" table="child" fetch="select"> <key> <column name="child_parent_code" not-null="true" /> </key> <one-to-many class="foo.bar.Child" /> </set> ``` In `Child.hbm.xml`: ``` <many-to-one name="parent" class="foo.bar.Parent" fetch="select"> <column name="child_parent_code" not-null="true" /> </many-to-one> ``` I've spent an hour poring through my copy of Java Persistence with Hibernate, but I can't figure out how to do what I want. Is it possible?