Advertisement



< Prev
Next >



Hibernate mapping Single Table Inheritance



Today we are going to understand how to map inheritance between the classes to the database using Hibernate. As you already know, inheritance is used when a class wants to use/inherit the features of another existing class.

The class that wants to use the feature of another class, is called subclass, whereas the class whose features are to be used/inherited is referred to as superclass. A class inheriting from another class, can access its features and can also add its own specific features.

Let's take an example of an Entity class - Country, which is extended by two classes AsianCountry and EurpoeanCountry. By default, Hibernate performs the inheritance between classes by combining all of their objects under single table and this strategy is also called Single Table Strategy. Now, let's see how Hibernate performs object-relational-mapping(ORM) to represent the inheritance between these three classes in the database.




Note :







Creating a primary/parent Entity class


We are going to create a general parent class that will contain all the Java code files representing our Model class(whose objects needs to be persisted). This parent class will be inherited by a few child classes that we are going to create later on.

This is a simple Java class whose objects needs to be persisted/saved, these objects are also known as Plain Old Java Objects(POJO) or Entity class. Some may even refer to such class whose objects needs to be persisted as the Model class.

Country.java
package decodejava;

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

@Entity
public class Country 
{
	@Id
	@GeneratedValue
	private int id;
	
	private String name;
	
	public String getName() 
	{
		return name;
	}
	
	
	public void setName(String name) 
	{
		this.name = name;
	}
	
	
}



Advertisement




Creating the first child Entity class


Next, we are going to create the child Entity class inheriting from the parent Country class. The object of this child class will also be persisted in the database table. The object of this class will contain a few specific properties such as continent and population to save these specifics about each country. This class is also an entity class, hence it will be preceded with the @Entity annotation.


AsianCountry.java
package decodejava;

import javax.persistence.Entity;

@Entity
public class AsianCountry extends Country 
{
	
	private String continent;
	private int population;

	public String getContinent() {
		return continent;
	}

	public void setContinent(String continent) {
		this.continent = continent;
	}
	
	
	public int getPopulation() 
	{
		return population;
	}
	
	
	public void setPopulation(int population) 
	{
		this.population = population;
	}
	

}





Creating the second child Entity class


Next, we are going to create another child Entity class inheriting from the parent Country class. The object of this child class will also be persisted in the database table. The object of this class will also contain a few specific properties to capture information about each country, such as its continent and population. This class is also an entity class, hence it will be preceded with the @Entity annotation.


EuropeanCountry.java
package decodejava;

import javax.persistence.Entity;

@Entity
public class EuropeanCountry extends Country 
{
	
private String continent;
private int population;


public String getContinent() 
{
	return continent;
}

public void setContinent(String continent) 
{
	this.continent = continent;
}


public int getPopulation() 
{
	return population;
}

public void setPopulation(int population) 
{
	this.population = population;
}

}





Creating the class that calls the Hibernate API


This class will create some objects of all the three classes(parent and its subclasses) involved in inheritance, which will be persisted using the Hibernate API and an object-relational mapping(ORM) in the database is performed.

The Hiber class creates a Configuration object, used to configure the Hibernate. This is the first object we use when using the Hibernate. This object is used to specify the location of a configuration file and mapping document used by Hibernate. Using Configuration object we can create a SessionFactory object, which is eventually used to create a Session object to perform the object persistence operations.

Note : We will not need to set the Id value of each object of parent class Country, as it is automatically done by using Hibernate's @GeneratedValue annotation.


Hiber.java
package decodejava;

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

public class Hiber 
{

	public static void main(String[] args) 
	{
		
		Configuration config = new Configuration();
		SessionFactory sf = config.configure().buildSessionFactory();
		Session session  = sf.openSession();
		
		
		Country country1 = new Country();
		country1.setName("Asian Country");
		
		AsianCountry asianCountry1 = new AsianCountry();
		asianCountry1.setName("Japan");
		asianCountry1.setContinent("Asia");
		asianCountry1.setPopulation(127000000);
	    
	    
		EuropeanCountry europeanCountry1 = new EuropeanCountry();
		europeanCountry1.setName("Germany");
		europeanCountry1.setContinent("Europe");
		europeanCountry1.setPopulation(87000000);
	    
	    
		session.beginTransaction();
		session.save(country1); //Saving the first Country object object
		session.save(asianCountry1); //Saving the first AsianCountry object
		session.save(europeanCountry1); //Saving the first EuropeanCountry object
		session.getTransaction().commit();
		session.close();	
	}

}





Adding JARs




Note : Those who don't know how to add JARs to the build path of your Java project in Eclipse IDE, please refer to our section Adding JARs to your Hibernate project in Eclipse.




Adding a configuration file




This configuration document ends with an extension .cfg.xml, and it is named as hibernate.cfg.xml.


This configuration file is an xml file and it allows us to specify the following features -


hibernate.cfg.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">



<hibernate-configuration>

<session-factory>


<!-- Database connection settings -->
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="connection.url">jdbc:oracle:thin:@localhost:1521:XE</property>
<property name="connection.username">system</property>
<property name="connection.password">promila21</property>


<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>


<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.Oracle10gDialect</property>


<!-- Disable the second-level cache  -->
<property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>
        
        
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>


<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">create</property>


<!-- Names the mapping entity class -->
<mapping class ="decodejava.Country"/>
<mapping class ="decodejava.AsianCountry"/>
<mapping class ="decodejava.EuropeanCountry"/>

</session-factory>

</hibernate-configuration>





Directory Structure of Hibernate Project




The picture above depicts how and where to arrange POJO/Entity(.java) file, its two child Entity classes and the class(that calls the hibernate into action) in a specific directory structure.

Project Folder - HibernateSingleTableInheritance is the name of our Project and it is a top-level directory.






Execution


When you execute the Hiber.java class, you will see the following output -

  • Hibernate: create sequence hibernate_sequence start with 1 increment by 1 Hibernate: create table Country (DTYPE varchar2(31 char) not null, id number(10,0) not null, name varchar2(255 char), continent varchar2(255 char), population number(10,0), primary key (id)) Hibernate: select hibernate_sequence.nextval from dual Hibernate: select hibernate_sequence.nextval from dual Hibernate: select hibernate_sequence.nextval from dual Hibernate: insert into Country (name, DTYPE, id) values (?, 'Country', ?) Hibernate: insert into Country (name, continent, population, DTYPE, id) values (?, ?, ?, 'AsianCountry', ?) Hibernate: insert into Country (name, continent, population, DTYPE, id) values (?, ?, ?, 'EuropeanCountry', ?)

  • This output shows you all the SQL commands executed by the Hibernate within the database to map the inheritance between the Java classes to a database table and perform all the activities of saving the objects of all three Entity classes.


    Finally, after executing Hiber class a new table will be constructed -



    Moreover, if you type the following SQL query in the database -

    select * from Country; 


    you will get the following output displaying -



    This table shows you how hibernate adds all the object of classes involved in inheritance relationship, within a single database table, where DTYPE column shows the class name of each object.




    Please share this article -




    < Prev
    Next >
    < ManyToMany Mapping with Mapping Resource
    ST Inheritance with Annotation(AN) >



    Advertisement

    Please Subscribe

    Please subscribe to our social media channels for daily updates.


    Decodejava Facebook Page  DecodeJava Twitter Page Decodejava Google+ Page




    Advertisement

    Notifications



    Please check our latest addition

    PYTHON and DJANGO


    Advertisement