How can I substitute a key object for a reference to the target class of an association?
Some classes in my application model an association to another class using a key object. In other words, the source of a relationship does not contain an instance of the associated object, but contains instead an identifier object for the associated instance. Here's an example:
Class Cat has a one-to-one relationship to its favorite food, a gerbil. Normally, this relationship is easily represented:
public class Cat {
private Food favorite = new Food("gerbil");
// other fields ...
}
public class Food {
private String species; // identifier for food type
// other fields follow...
}
However, I want to replace the instance of Food with an instance of some identifier for Food, FoodId:
public class Cat {
private FoodId favoriteId = new FoodId("gerbil");
// other fields follow...
}
public class FoodId {
private String species; // FoodId contains only the id field for Food
}
The database table for Cat contains a foreign key column that refers to the Food table.
How can I represent this relationship in Hibernate? I attempted to create two hibernate mappings for the Food table -- one for the Food class, and another for the FoodId class that maps only the identifier field. However, I can't get hibernate to manage the foreign key columns properly. In addition, the docs say that only a single object should be associated to a given DB row for a given session. Consequently, I can't have both the FoodId instance and a Food instance mapped to the same DB row.
Thanks for any help.
Dave[/quote]
|