Following is a description that is been taken (extract) from
Java Persistence book. Credit goes to the authors. I just worded a different similar example.
This is a case that I know where it can be used. Suppose we have two (it can be as many as possible) classes (that has some common/general properties) in Java and one table to represent this in database. I mean we would like to persist both the objects into a single table.
Example scenario:
Code:
public abstract class Attachment {
- String name;
- ETC
}
public ImageAttachement extends Attachment {
- Integer imageSizeWidth;
- Integer imageSizeHeight;
- String imageType;
}
public TextAttachment extends Attachment {
- Integer size;
}
We have only one table (to represent this class hierarchy) called
attachment (attachment_id number, type varchar(1), name varchar(25), image_size_width number, image_size_height number, image_type varchar(3), size number)
Hibernate mapping:Code:
<class
name="Attachment"
table="attachment">
<id
name="id"
column="attachment_id"
type="long">
<generator class="native"/>
</id>
<discriminator
column="attachment_type"
type="string"/>
<property
name="sentBy"
column="sent_by"
type="string"/>
...
<subclass
name="ImageAttachment"
discriminator-value="IMG">
<property name="imageSizeWidth" column="image_size_width"/>
<property name="imageSizeHeight" column="image_size_height"/>
<property name="imageType" column="image_type"/>
</subclass>
<subclass
name="TextAttachment"
discriminator-value="TXT">
...
</class>
Since we are storing two objects into a single table, for persistence and retrieval purposes, since Hibernate handles this automatically and internally, we have to have a special column in the table to distinguish between these two persistent classes: the discriminator.
Please note that there is
NO such property in the persistent classes. This discriminator is used
internally by Hibernate. Hibernate will set correct values ('IMG" or "TXT") for this discriminator column automatically.
Hope this helps.