dev-blog

Tuesday, January 11, 2005

Can Hibernate map one class to more than one table?

One restriction with Hibernate seems to be that one java class can be mapped to maximum one table.

Example:

Imagine a catalog of product objects which are cloned before they are assigned to an order.
This scenario can not be implemented with hibernate provided the ordered products should be persited into a separate table i.e. not the product-catalog table.

One solution for this might be to copy the catalog product objects into objects of an other class (maybe called LineItem). Objects of this class can then be mapped into an other table.

An other question is how to implement the different characteristics of different product-types:

Option 1: Each product-type is modelled as a sub-class (extension) of a base Product. Properties specific to a product-type are added to the sub class. Hibernate is supporting this model by allowing to map all sub-classes to one database table.
One specific sub-class of the product and therefore also a product-type is modelled as container for other products. This (bundle-) product can contain any type of other product object as child products.

Option 2: We have only one generic product class and the product-type is modelled as an enumerated value. Properties specific to a product-type are modelled as generic containers (e.g. one string value and one numeric value) which are to be interpreted diffently depending on the product-type. This generic product can also contain other product objects as child products (i.e. each type of a product can be a bundle product).

Conclusions:
Option 1 can be considered as "cleaner" object oriented design but probably also the more complicated solution. Especially when considering the above mentioned restriction of Hibernate (a class can not be mapped to more than one table). This would result in a duplicating the complete class hierarchy. Option 2 is a more generic but less strongly typed. As long as we can live with it's restrictions I consider this solution the one with lower implementation effert.

0 Comments:

Post a Comment

<< Home