Hibernate Version: 3.0
We have three persistent classes, P1, P2, and Description. P1 and P2 both have a collection of Description entities. This setup works fine if we define our mappings like this:
Code:
<hibernate-mapping>
<class name="com.am.t.beans.P1" table="p1">
<id name="id" unsaved-value="0">
<generator class="native"/>
</id>
<property name="name" type="string"/>
<map name="descriptions"
lazy="true"
cascade="all">
<key column="p1Id"/>
<map-key formula="type" type="string"/>
<one-to-many class="com.am.t.beans.Description"/>
</map>
</class>
</hibernate-mapping>
Code:
<hibernate-mapping>
<class name="com.am.t.beans.P2" table="p2">
<id name="id" unsaved-value="0">
<generator class="native"/>
</id>
<property name="name" type="string"/>
<map name="descriptions"
lazy="true"
cascade="all">
<key column="p2Id"/>
<map-key formula="type" type="string"/>
<one-to-many class="com.am.t.beans.Description"/>
</map>
</class>
</hibernate-mapping>
Note that in P1's description collection, the key column is P1id, and in P2's collection the key column is P2id. The 'description' table hibernate creates looks like this:
Code:
+-----------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------+--------------+------+-----+---------+----------------+
| id | bigint(20) | | PRI | NULL | auto_increment |
| type | varchar(255) | YES | | NULL | |
| text | varchar(255) | YES | | NULL | |
| p1Id | bigint(20) | YES | MUL | NULL | |
| p2Id | bigint(20) | YES | MUL | NULL | |
+-----------+--------------+------+-----+---------+----------------+
This setup works properly with Hibernate.
But in some cases we may have P3, P4, P5, and P6 similar to P1 and P2. In this situation, if we used the approach above, the Description table would have p1id, p2id, p3id, p4id, p5id, and p6id. From a database perspective, we would rather define the Description table like this:
Code:
+-----------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------+--------------+------+-----+---------+----------------+
| id | bigint(20) | | PRI | NULL | auto_increment |
| type | varchar(255) | YES | | NULL | |
| text | varchar(255) | YES | | NULL | |
| pid | bigint(20) | YES | MUL | NULL | |
| ptype | varchar | YES | MUL | NULL | |
+-----------+--------------+------+-----+---------+----------------+
So that the ID of any P entity (1-6) would go in the 'pid' column. The 'ptype' column would contain, ie, "p1", "p2", "p3" etc... In other words, we would store in the table the type and id of the P entity related to this description.
Is there any way in hibernate to mimic this sort of setup?
Thanks!