tags:

views:

152

answers:

2

I have to map a lecagy database for read-only purposes that contains the following structure:

Table MAIN: 
id productId productType

Table PRODUCT_A: 
id description_a

Table PRODUCT_B: 
id description_b

Table PRODUCT_C: 
id description_c

Depending on the value in column productTyp, the productId refers either to the PRODUCT_A,PRODUCT_B, or PRODUCT_C.

For each of the tables I create a Java entity. The Main class contains one collection for each product.

The products are not in a 'is a' relationship with the main class. It is used under other circumstance as independent entity.

Is there any way to map this using hbm.xml files?

+3  A: 

Look like you are looking for inheritance using the table per sub class strategy using a discriminator. In Java each PRODUCT_X class should extend the Main class. This page explains the details of implementing this strategy.

Vincent Ramdhanie
looked to me like I could use inheritance, too, but the product classes are far from being in a 'is a' relationship to main
bertolami
Remember that you are not doing OO design here, rather you are finding the most effective way to map the existing tables. If you had the luxury of redesigning the table structure then I would be concerned about whether inheritance is the best solution or not. But since thats not the case. Unfortunately we have to compromise a little to get the job done.
Vincent Ramdhanie
agree. but since there are many other tables involved I still hesitate.
bertolami
@Vincent - I strongly disagree with your comment. Sacrificing domain model clarity is **NEVER** the right choice. Even assuming that `<any>` mapping (see my answer) was not supported by Hibernate, the next best choice would have been to map ProductX as table-per-concrete-class and obtain the needed instance via implicit polymorphism.
ChssPly76
@ChssPly76 I am actually in agreement with you on this. I was assuming that the OP has no control over the DB structure etc and just need a quick fix. So you are completely right to disagree with my comment.
Vincent Ramdhanie
+2  A: 

The proper way to map this is via <any>:

<class name="Main" table="MAIN">
  ...
  <any name="product" id-type="long" meta-type="string">
    <meta-value value="PRODUCT_A" class="ProductA"/>
    <meta-value value="PRODUCT_B" class="ProductB"/>
    <meta-value value="PRODUCT_C" class="ProductC"/>
    <column name="productType"/>
    <column name="productId"/>
  </any>
</class>

You'll have to map the appropriate ProductA etc... classes to corresponding tables (perhaps you already have).

ChssPly76