Next Previous Index

9. Subclasses


Definition:

Subclasses are first-rank classes that extend another first-rank class in a standard OO inheritance relationship.


Scenario:

We have one first-rank class, Foo, and another first-rank class, Bar, which is a subclass of Foo.


public class Bar extends Foo // Bar is a subclass of Foo

Hibernate Mapping:

In Hibernate, this could be mapped as follows:


<class name="Foo" table="foo"  discriminator-value="F">
    ...
    <discriminator column="class"/>
    ...
    <subclass name="subclass.Bar" discriminator-value="B">
         <property name="name" column="name" type="string"/>
    </subclass>
</class>

Table Schema:

Foo

id

class

name


The class field holds a discriminator value. This value tells Hibernate which Java class to instantiate on loading. The subclass, Bar, has its properties stored in the Foo table.


NB: In this case we've used one table per class hierarchy. An alternative would be one table per concrete class. We could map that by simply including two class definitions and repeating the attributes of Foo in the Bar definition.


Bidirectionality:

Inheritance relationships are only unidirectional in Java. A child can determine its parent class but the reverse has no meaning.



Next Previous Index