Mapping an entity to multiple tables using a join

5 views
Skip to first unread message

Jeremy Jarrell

unread,
Aug 13, 2008, 10:39:22 AM8/13/08
to nhusers
Hi,

I have two tables that I need to join on a column in the mapping
file. For example, imagine I have two tables: Cars and Engines. Cars
columns for ID, Color, TopSpeed, and EngineID. Engines has columns
for ID and NumCylinders.

Now, imagine my Car entity class has properties for ID, Color,
TopSpeed, and NumberOfCylinders. I can easily map ID, Color, and
TopSpeed to the corresponding columns in the Cars table, but how I can
map NumberOfCylinders to the Engines table where Cars.EngineID =
Engines.ID?

I'd like to accomplish this in the mapping file, but I'm not quite
sure how to supply the respective column names in each table to join
on.

<class name="Car">
<id name ="ID">
<generator class="guid"/>
</id>
<property name="Color"/>
<property name="TopSpeed"/>
<join table="Engines">
<key column="ID"/> <--how do i specify the joining columns
here?-->
<property name="NumberOfCylinders" column="NumCylinders"/>
</join>
</class>

Any help would be greatly appreciated.

Thanks!
Jeremy
</hibernate-mapping>

Jason Meckley

unread,
Aug 14, 2008, 10:39:53 AM8/14/08
to nhusers
number of cylinders is directly related to the engine, not the car. A
car has an engine and Car can be an aggregate. I would expose a
property on Car which references the engine.

public class Car
{
private Engine engine;

public int NumberOfCylinders
{
get { return engine.CylinderCount; }
}
}

<class name="Car">
<id name ="ID">
<generator class="guid"/>
</id>
<property name="Color"/>
<property name="TopSpeed"/>
<many-to-one name="engine" class="Engine" column="engine_id" not-
null="true" access="nosetter.camelcase" />
</class>
<class name="Engine">
<id name ="ID">
<generator class="guid"/>
</id>
<property name="NumberOfCylinders"/>
<bag name="cars" table="car" ... >
<key column="order_number" />
<one-to-many class="Car" />
</bag>
</class>

Jeremy Jarrell

unread,
Aug 14, 2008, 10:57:00 AM8/14/08
to nhu...@googlegroups.com
Thanks, Jason!
--
Jeremy Jarrell
www.JeremyJarrell.com
Reply all
Reply to author
Forward
0 new messages