Tuesday, July 5, 2011

Mapping Entities with Inheritance

Again there are a number of ways Hibernate can handle inheritance. These are based on the standard techniques for reducing generalisation hierarchies in entity-relationship diagrams.

The simplest is to use one table for the whole hierarchy. With this design, each row of the table can hold an object of any type from the hierarchy. There is one column for each of the properties in the union of the sets of properties of all the classes in the hierarchy and there is one discriminator column which contains a value (usually of type string, character or integer) used to tell which actual type of object is stored in this particular row. One normally does not make this discriminator a property of the class: it is used only by Hibernate to record and detect the type of the object that a row represents.
An Inheritance Class Hierarchy

<class name="Person" table="people" discriminator-value="P">
    <id name="id" column="id" type="long">
        <generator class="sequence"/>
    <version  name="version"         column="version"/>
    <discriminator column="subclass" type="character"/>
    <property name="dateOfBirth"     column="dob" type="date"/>
    <property name="name"/>
    <property name="gender"/>
    <subclass name="Lecturer" discriminator-value="L">
        <property name="office" type="string"/>
        <property name="telephone" type="string"/>
    <subclass name="Student" discriminator-value="D">
        <property name="studentID" type="integer"/>

Here one may not specify any of the subclass fields as not null because the corresponding column will be null in the table for any object of the hierarchy which is not of the subclass that contains the relevant property for that column.

No comments:

Post a Comment