Skip to content

Inheritance patterns: Table Per Concrete Class Inheritance

G4br13l3 edited this page Sep 3, 2015 · 18 revisions

Table Per Concrete Class Inheritance

In Table Per Concrete Class strategy a table is defined for each concrete class in the inheritance hierarchy to store all the attributes of that class and all of its superclasses. This strategy is optional in several ORM technologies (e.g. JPA), and querying root or branch classes can be very difficult and inefficient.

Example

Now suppose you want to map the whole hierarchy given below into a coherent relational database schema. The Employee class is a superclass both for Regular_Employee and Contract_Employee classes.
The described pattern application leads to the DB schema shown in the following diagram:

There are two equivalent mapping file for this hierarchy:
1.

<?xml version='1.0' encoding='UTF-8'?>  
<!DOCTYPE hibernate-mapping PUBLIC 
   "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
   "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">


<hibernate-mapping>
	<class name="Employee" table="employee">
		<id name="id">
			<generator class="increment"></generator>
		</id>

		<property name="name"></property>

		<joined-subclass name="Regular_Employee"
			table="regular_employee">
			<key column="eid"></key>
			<property name="salary"></property>
			<property name="bonus"></property>
		</joined-subclass>

		<joined-subclass name="Contract_Employee"
			table="contract_employee">
			<key column="eid"></key>
			<property name="pay_per_hour"></property>
			<property name="contract_duration"></property>
		</joined-subclass>
	</class>
</hibernate-mapping>      
<?xml version='1.0' encoding='UTF-8'?>  
<!DOCTYPE hibernate-mapping PUBLIC 
   "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
   "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">


<hibernate-mapping>
	<class name="Employee" table="employee">
		<id name="id">
			<generator class="increment"></generator>
		</id>
		<discriminator column="employee_type" type="string" />
		<property name="name"></property>

		<subclass name="Regular_Employee" discriminator-value="R">
			<join table="regular_employee">
				<key column="eid"></key>
				<property name="salary"></property>
				<property name="bonus"></property>
			</join>
		</subclass>

		<subclass name="Contract_Employee" discriminator-value="C">
			<join table="contract_employee">
				<key column="eid"></key>
				<property name="pay_per_hour"></property>
				<property name="contract_duration"></property>
			</join>
		</subclass>
	</class>
</hibernate-mapping>  

Exploiting the inheritance-feature offered by Teleporter, in OrientDB you will get the following schema:

If you deal with a multi-level inheritance relationships in the DB, you have to represent them in the ORM file by recursively nesting each definition according to the hierarchical dependences being between the Entities of the model.