Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to implement inheritance for a single table in hibernate

In this article, we will learn about the need for inheritance in ORM Tools and implementation of inheritance with ORM Tools.

Inheritance, is the one of important feature of OOP that is used to passing its properties to child or sub classes. It is the way of establishing is-a relationship between class objects that inherit attributes and behavior of base class. It is the way of implementing polymorphism using method overriding. When we use inheritance with Object Relational Mapping Tools, it inherits the mapping attributes and behavior of base class to entity sub – classes .

Inheritance for Tables in Hibernate in detail:

We have to main reason to use inheritance with ORM tools mapping:

  • If we’ve the user class that has vehicle information to be saved. Without inheritance, it would necessary to save all the information about list of all kinds of vehicles. But by inheritance mapping, we will need to have vehicle id that will represent these different kind of vehicles.
  • The another reason is to update any vehicle property in future is made easy using mapping inheritance.

Let’s have an example to better understand the need of inheritance. We have a user class that manage information about user vehicles in itself. We can assign only one object of an entity class at a time and if we have multiple vehicle class type. This problem can be resolved using inheritance, where these vehicle type classes can be inherited by vehicle base class.

First of all create an entity class ‘Vehicle’ that is the base class as listed in listing 1.

Listing 1: Vehicle.java

package inheritance;

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

@Entity
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 the Vehicle Entity Base class that defines two class variables ‘id’ and ‘name’ with its getter() and setter() methods. @Entity annotation is used to define this class as entity class that is defined in javax.persistence.Entity package. Two more annotations ‘@id’ and ‘GeneratedValue’ are defined in javax.persistence.GeneratedValue and javax.persistence.Id classes respectively.

We inherit one class TwoWheeler that inherits Vehicle as listed in Listing 2:

Listing 2: TwoWheeler.java

package inheritance;

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 java class that inherits properties of Vehicle class and defines a String type variable ‘SteeringWheel’ with its getter() and setter() methods. @Entity annotation defines this class as an entity class.

The next class FourWheeler is also inherited by Vehicle class as listed in Listing 3:

Listing 3: FourWheeler.java

package inheritance;

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 code defines the FourWheeler.java java class that inherits the properties of Vehicle class and also defines a String type variable ‘SteeringHandle’ with its getter() and setter() methods.

These entity classes are instanctiated in ‘CreateVehicle’ class that a database table to store schema for these three entities classes as listed in Listing 4.

Listing 4: CreateVehicle.java

package inheritance;

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

public class CreateVehicle {
	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 table defines a main() method. This method defines Configureation insatance that configures the “hibernate.cfg.xml” file and create SessionFactory class object to buildSessionFactory based on “hibernate.cfg.xml” configuration file. A Session class object is being created using SessionFactory class method openSession().

Once we have done with this, we create instances for Vehicle, TwoWheeler and FourWheeler classes respectively and initialize their data variables.

A session transaction is being started using beginTransaction() method of Session class and save entity objects using save() mehtod of Session class.

Now commit the beingTransaction using session.getTransaction.commit() method and close session using session.close() method.

Once we have done this configuration, define the entity class type in hibernate.cfg.xml file as listed in Listing 5.

Listing 5: hibernate.cfg.xml

<?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 = "inheritance.Vehicle"/>
		<mapping class = "inheritance.TwoWheeler"/>
		<mapping class = "inheritance.FourWheeler"/>
	</session-factory>
</hibernate-configuration>

The above code defines the hibernate.cfg.xml configuraiton file that defines the database type and connection information. The database driver name is defined using:

<property name="connection.driver_class">com.mysql.jdbc.Driver</property>

The next tag defines the mysql database connect url, user and password:

 <property name="connection.url">jdbc:mysql://localhost/test</property>
       <property name="connection.username">root</property>

The next xml tag statements defines the class mapping:

<mapping class = "inheritance.Vehicle"/>
	<mapping class = "inheritance.TwoWheeler"/>
	<mapping class = "inheritance.FourWheeler"/>

We are required a set of jar files to run this hibernate application, Figure 1 shows the list of required jar file as:

List of jar files Required

Figure 1: List of jar files Required

The above figure shows list of jar files required to run this application. It list the MySql database connector and hibernate jar files bundle.

The figure 2 shows the project structure created in Eclispe IDE:

Project Structure created in Eclipse IDE

Figure 2: Project Structure created in Eclipse IDE

The figure shows the ‘inheritance’ package that contains all three entity class files and main class file ‘CreateVehicle.java’ that creates Vehicle database table to mysql database.

Once we have done all the configuration and implementation part of the application, run the application using ‘CreateVehicle.java’ file. Run this file as java application:

Right click on the class file and choose ‘Run As->Run as Java Application’ as shown in Figure 3.

Run CreateVehicle.java class file

Figure 3: Run CreateVehicle.java class file

The execution of the ‘CreateVehicle.java’ class file creates Vechicle database table with its schema as shown in Figure 4.

Vehicle Database Schema Create Log in Console

Figure 4: Vehicle Database Schema Create Log in Console

Figure 4 shows the database entry log into the console. It shows three entries made into the vehicle database table.

Now, lets check for database record updated into the mysql database. It is shown in Figure 5:

Vehicle Database Table with its Records in MySql Database

Figure 5: Vehicle Database Table with its Records in MySql Database

The above figure shows vehicle database table created into the MySql database.

As we have seen above, Hibernate creates a single table for these three entity classes. If there is an entry to vehicle table, ‘SteeringWheel’ colum and ‘SteeringHandle’ column rerord will remain empty and for ‘TwoWheel’ entity class, ‘SteeringHandle’ will remain empty and for ‘FourWheeler’ class, ‘SteeringWheel’ will remain empty.

Required Tools:

To create this application, we are required following list of tools and application:

  • JDK run time environment (Ex. JDK 7)
  • Eclipse IDE (Ex. Eclipse Juno)
  • Hibernate Jar Files
  • MySql Database Installed
  • MySql Connector Jar File

Conclusion:

In this article, we learn about the inheritance and its requirement in hibernate object relational mapping tool. Inheritance gives us the way to assign and manage multiple entity types to a single object entry using its base class.



Software developer with more than 5 years of development on Java, HTML, CSS.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login