An inheritance is the way of inheriting parental properties into its sub classes or derived classes. In Hibernate, Inheritance is used among database tables. By default, Inheritance works for single class table strategy and creates a single table for its parent and sub classes. In Hibernate, we can also create multiple tables or tables per class and sub class strategy or for table join relationship.

Tables per Class Strategy by Inheritance in Detail:

In Hibernate, There are multiple strategies available by inheritance to create table and manage tables as:

  • Single Table Strategy
  • Table per class Strategy
  • Join Table for class and sub class Strategy

To create a single table strategy, we use:

  • @Inheritance(strategy=InheritanceType.SINGLE_TABLE): To define discriminator column with column name and column datatype as:
  • @DiscriminatorColumn(name="VEHICLE_TYPE",discriminatorType=DiscriminatorType.STRING):To define values into for Discriminator type column in its sub classes using annotation:
  • @DiscriminatorValue(“Bike”)

In this article, we are going to talk about “Table per class Strategy”. We shall use few kind of annotations that will help us to create “Table per class Strategy” by inheritance.

In this case, We will have to define the InheritanceTyp1e to TABLE_PER_CLASS strategy.

And there is no need to define any DiscriminatorType Column in the base class and DiscriminatorValues in the sub – classes. All the classes should be defined as an Entity class.

Now, Let's go with the an example that will create “TABLE_PER_CLASS” strategy using Vehicle base and its two derived classes TwoWheeler and FourWheeler classes as:

array0

Required Tools:

We are required to have following tools and applications to write and run this example:

  • Eclipse IDE
  • JDK 7 Run time environment
  • MySql Database

Required Jar Files:

There is required a set of hibernate jar files and MySql connector jar file as shown in Figure 1:

Set of jar files required for Hibernate and MySql

Figure 1: Set of jar files required for Hibernate and MySql

Directory Structure:

A directory structure is created by Eclipse Ide as shown in Figure 2:

Directory Structure created by Eclipse IDE

Figure 2: Directory Structure created by Eclipse IDE

Now create Vehicle.java class as listed in Listing 1:

Listing 1: Vehicle.java

package table;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;

@Entity
@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
public class Vehicle {
	@Id @GeneratedValue
	private int id;
	private String name;
	
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
		
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}	
}

The above code defines a Vehicle class that declares two class member variable of Int and String type with its getter() and setter() methods. This class is defined as an entity class using @Entity annotation. This annotation is defined in javax.persistenc package. The next annotation @GeneratedValue is used to insert auto – incremented record in id column of database table.

One more annotation @Inheritance is used to define the inheritance strategy type. It defines the TABLE_PER_CLASS strategy as :

array0

Now define a sub – class TwoWheeler of Vehicle base class as an entity class. This class will create a new table into the database as “TwoWheeler” by inheriting base class properties as listed in Listing 2.

Listing 2: TwoWheeler.java

package table;

import javax.persistence.Entity;

@Entity
public class TwoWheeler extends Vehicle{
	private String SteeringWheel;

	public String getSteeringWheel() {
		return SteeringWheel;
	}

	public void setSteeringWheel(String steeringWheel) {
		SteeringWheel = steeringWheel;
	}
}

The above code defines a TwoWheeler class that extends Vehicle class. This class inherits the properties of Vehicle base class and declares a String type class member variable with its getter() and setter() methods. This class is defined as an entity class using @Entity annotation. Hence, It will create a separate table into the databaes by name “TwoWheeler”.

Now lets define one more sub – class FourWheeler of Vehicle base class as listed in Listing 3:

Listing 3: FourWheeler.java

package table;

import javax.persistence.Entity;

@Entity
public class FourWheeler extends Vehicle{
	private String SteeringHandle;

	public String getSteeringHandle() {
		return SteeringHandle;
	}

	public void setSteeringHandle(String steeringHandle) {
		SteeringHandle = steeringHandle;
	}	
}

The above class defines a FourWheeler class that inherits the properties of Vehicle base class. It defines a String type class member variable with its getter() and setter() methods. This class is defined as an entity class using @Entity annotation. Hence, It will create a separate table into the databaes by name “FourWheeler”.

Now, Let's define a class that will create instances of these entity classes and will save these instances into the database using hibernate configuration as listed in Listing 4:

Listing 4: Table_Per_Class.java

package table;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class Table_Per_Class {
	public static void main(String[]args){
		Configuration cfg = new Configuration();
		cfg.configure("hibernate.cfg.xml");
		SessionFactory sessionFactory = cfg.buildSessionFactory();
		Session session = sessionFactory.openSession();
		
		Vehicle vechicle = new Vehicle();
		vechicle.setId(1);
		vechicle.setName("vechicle");
		
		TwoWheeler twoWheeler = new TwoWheeler();
		twoWheeler.setId(2);
		twoWheeler.setName("vechicle");
		twoWheeler.setSteeringWheel("TwoWheeler");
		
		FourWheeler fourWheeler = new FourWheeler();
		fourWheeler.setId(2);
		fourWheeler.setName("vechicle");
		fourWheeler.setSteeringHandle("FourWheeler");
		
		session.beginTransaction();
		session.save(vechicle);
		session.save(twoWheeler);
		session.save(fourWheeler);
		
		session.getTransaction().commit();
		session.close();
	}
}

The above coding defines the Table_Per_Class strategy type. This class defines a main() method. This method declares instances for class Vehicle, TwoWheeler and FourWheeler classes to initialize class member variables.

It also defines an instance of Configuration class type that call configure() method to read hibernate-cfg.xml configuration file. Now, Crate an instance of SessionFactory class using method buildSessionFactory() method of Configuration class. Using SessionFactory instance, call method openSession() and assign its reference to Session class type instance.

The SessionFactory instance is created for once for an application and a session instance is created for every time, whenever database communication is required.

Now to save entity class objects into the database, call beginTransaction() method and call save() methods for each entity objects. Once we have saved these objects into the database, commit the opened transaction using method session.getTransaction.commit() and close the session using method close().

Now define a hibernate-cfg.xml configuration file in Listing 5:

Listing 5: hibernate-cfg.xml file

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<!-- Generated by MyEclipse Hibernate Tools.                   -->
<hibernate-configuration>

    <session-factory>
    	<!-- Database Connection Settings -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost/test</property>
        <property name="connection.username">root</property>
        <property name="connection.password"></property>
        
        <!-- JDBC Connection Pool (Use the built-IN) -->
        <property name="connection.pool_size">1</
        property>
        
        <!-- Diable the second-level cache -->
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
        
        <!-- Database Schema Modification Type -->
        <property name="hbm2ddl.auto">create</property>
        
        <!-- Database Dialect -->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        
        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>
        
        <!-- Hibernate Class Mapping -->
		<mapping class = "table.Vehicle"/>
		<mapping class = "table.TwoWheeler"/>
		<mapping class = "table.FourWheeler"/>
	</session-factory>
</hibernate-configuration>

The above code defines hibernate configuration file. This code define tag to inform the hibernate about the set of entity classes that will be manipulated as entity type for hibernate.

Once we have gone through all this configuration and coding, to execute this application right click on the “Table_Per_Class” java file and choose “Run As” and select “Run As Java Application”. This will produce three tables “Vehicle”, “TwoWheeler” and “FourWheeler” as shown in Figure 3:

Table Created by hibernate

Figure 3: Table Created by hibernate

Conclusion

In this article, we learn about all different kind of Inheritance strategies provided for hibernate to create database tables in different ways. We also created an example for TABLE_PER_CLASS strategy of inheritance.