bertolami
bertolami

Reputation: 2936

Hibernate Mapping Conditional Many-To-One

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?

Upvotes: 2

Views: 1807

Answers (2)

ChssPly76
ChssPly76

Reputation: 100706

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).

Upvotes: 2

Vincent Ramdhanie
Vincent Ramdhanie

Reputation: 103135

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.

Upvotes: 3

Related Questions