Table Per Class Example Hibernate

Table Per Class Example Hibernate

Table Per Class Hierarchy

Note: Before going through this application, it is advised to read Hibernate Mapping Tutorial.

In this Table Per Class style, only one table is created with sufficient columns to accommodate all the properties of each class involved in hierarchy. Because all the records of each class are available in a single table, to differentiate which record belongs to which class, we create one extra column known as discriminator column. Each class identified by some name (say, alias name written in the mapping file) and this name is stored in the discriminator column.

In this Table Per Class approach, the Programmer should be careful that super class and subclass variables should not conflict (should not be the same). If such a situation comes, rename the field either in super class or subclass. In the table, for each record some columns will be empty; those columns for which the particular Java class does not have fields.

Table EMPTABLE does not exist. Let create it.

Let us write one client program for three bean programs – Employee, PermanentEmployee, TemporaryEmployee and two XML files – Employee.hbm.xml and hibernate.cfg.xml. Total 6 files.

Following is the Hierarchy of classes involved. Output screens are shown the end of this notes.

Table Per Class

Let us create Java classes for the above hierarchy.

1. File Name:

2. File Name:

3. File Name:

4. File Name: hibernate.cfg.xml

5. File Name: Employee.hbm.file

6. Client Program:

Table Per Class

Screenshot of MyEclipse Console. Observe four SQL statements are executed by Hibernate to persist four Java objects.

Table Per Class

  1. Observe, the table structure created automatically by Hibernate for the fields of three bean classes. For short data type, it is NUMBER(5) column type is created.
  2. Observe the four records. Some records columns are empty. For example, for temporary employee, columns DESIGNATION and DEPARTMENT are empty as TemporaryEmployee does not contain these fields.
  3. There is a limitation of mapping strategy with table-per-class. Certain columns declared by the subclasses, such as designation etc., cannot have NOT NULL constraints.
  4. Observe the discriminator (DIS) column. It is very special for table-per-class-hierarchy.

Let us write one more client program to retrieve the records separately of permanent and temporary employee.


Table Per Class

Observe all the records of PermanentEmployee are retrieved once (only one SQL statement is executed) and similarly for TemporaryEmployee.

Leave a Reply

Your email address will not be published. Required fields are marked *