Inheritance in Hibernate Basics and Table per Hierarchy

Inheritance in Hibernate

Inheritance1

Hibernate supports its own way of persisting the objects which have parent child relationship in Java.
Now let’s try to explore our own ways of saving the objects of the above hierarchy.

Any individual can come with some assumption like as below
1)I can save all the objects parent and child attributes in one single table(so one and only one table for the above diagram)
Persisting parent and child goes to same table.
2)I want to create individual tables for each class (so 3 tables for the above diagram)
Persisting parent should go in parent table. Persisting child should go in child table.
No relationship between parent and child tables.
All the attributes of parent(including those inherited from parent will become again a columns in each child)
3)Mostly the 3rd one is bit tricky and some intelligence is required – same concept as 2nd idea but instead of keeping all attributes of parent in child as well, we do keep a mapping between parent and child. So that parent data will not be repeated in child table.

Now Hibernate calls the those ideas as below
1)Single Table per Hiberrachy
2)Table per concrete class
3)Table per sub class

Lets see examples
1)Single Table per Hiberrachy
Create configuration file

1) hibernate.cfg.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?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">
<hibernate-configuration>  
    <session-factory>  
        <property name="hbm2ddl.auto">update</property>  
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>  
        <property name="connection.url">jdbc:mysql://localhost:3306/HibernateDB</property>  
        <property name="connection.username">root</property>  
        <property name="connection.password">kb</property>  
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="show_sql">true</property>
    <mapping resource="com/kb/hbmFiles/Person.hbm.xml"/>  
    </session-factory>  
</hibernate-configuration>  
<?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">
<hibernate-configuration>  
    <session-factory>  
        <property name="hbm2ddl.auto">update</property>  
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>  
        <property name="connection.url">jdbc:mysql://localhost:3306/HibernateDB</property>  
        <property name="connection.username">root</property>  
        <property name="connection.password">kb</property>  
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="show_sql">true</property>
    <mapping resource="com/kb/hbmFiles/Person.hbm.xml"/>  
    </session-factory>  
</hibernate-configuration>  

2)Create Person class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package com.kb.model;
 
public class Person {
    private long personId;
    private String firstName;
    private String lastName;
    public Person(String firstName, String lastName) {
        this.firstName=firstName;
        this.lastName=lastName;
    }
    public long getPersonId() {
        return personId;
    }
    public void setPersonId(long personId) {
        this.personId = personId;
    }
    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    
 
}
package com.kb.model;

public class Person {
	private long personId;
	private String firstName;
	private String lastName;
	public Person(String firstName, String lastName) {
		this.firstName=firstName;
		this.lastName=lastName;
	}
	public long getPersonId() {
		return personId;
	}
	public void setPersonId(long personId) {
		this.personId = personId;
	}
	public String getFirstName() {
		return firstName;
	}
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}
	public String getLastName() {
		return lastName;
	}
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}
	

}

3)create Employee class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package com.kb.model;
 
import java.util.Date;
 
public class Employee extends Person {
    
    private Date joiningDate;
    private String departmentName;
    
    public Employee(String firatName, String lastname, String dName, Date joiningDate) {
        super(firatName,lastname);
        this.joiningDate=joiningDate;
        this.departmentName=dName;
    }
    public Date getJoiningDate() {
        return joiningDate;
    }
    public void setJoiningDate(Date joiningDate) {
        this.joiningDate = joiningDate;
    }
    public String getDepartmentName() {
        return departmentName;
    }
    public void setDepartmentName(String departmentName) {
        this.departmentName = departmentName;
    }
 
}
package com.kb.model;

import java.util.Date;

public class Employee extends Person {
	
	private Date joiningDate;
    private String departmentName;
    
	public Employee(String firatName, String lastname, String dName, Date joiningDate) {
		super(firatName,lastname);
		this.joiningDate=joiningDate;
		this.departmentName=dName;
	}
	public Date getJoiningDate() {
		return joiningDate;
	}
	public void setJoiningDate(Date joiningDate) {
		this.joiningDate = joiningDate;
	}
	public String getDepartmentName() {
		return departmentName;
	}
	public void setDepartmentName(String departmentName) {
		this.departmentName = departmentName;
	}

}

4)create person.hbm.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
 
<hibernate-mapping package="com.kb.model">
 
    <class name="Person" table="PERSON" discriminator-value="P">
        <id name="personId" column="PERSON_ID">
            <generator class="native" />
        </id>
 
        <discriminator column="DISCRIMINATOR" type="string" />
 
        <property name="firstName" />
        <property name="lastName" column="lastname" />
 
        <subclass name="Employee" extends="Person" discriminator-value="E">
                <property name="departmentName" column="department_name" />
                <property name="joiningDate" type="date" column="joining_date" />
        </subclass>
    </class>
</hibernate-mapping>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
 
<hibernate-mapping package="com.kb.model">
 
    <class name="Person" table="PERSON" discriminator-value="P">
        <id name="personId" column="PERSON_ID">
            <generator class="native" />
        </id>
 
        <discriminator column="DISCRIMINATOR" type="string" />
 
        <property name="firstName" />
        <property name="lastName" column="lastname" />
 
        <subclass name="Employee" extends="Person" discriminator-value="E">
                <property name="departmentName" column="department_name" />
                <property name="joiningDate" type="date" column="joining_date" />
        </subclass>
    </class>
</hibernate-mapping>

5)Client code which acts as DAO

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package com.kb.dao;
 
import java.util.Date;
 
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
 
import com.kb.model.Employee;
import com.kb.model.Person;
 
public class DBInteract {
    
    public static void main(String[] args) {
         
         //creating configuration object  
        Configuration cfg=new Configuration();  
        
        cfg.configure("hibernate.cfg.xml");//populates the data of the configuration file  
          
        //creating seession factory object  
        SessionFactory factory=cfg.buildSessionFactory();  
          
        Session session = factory.openSession();
        session.beginTransaction();
 
         
        Person person = new Person("kb", "gc");
        session.save(person);
 
        Employee employee = new Employee("raj", "kumar", "financing", new Date());
        session.save(employee);
         
        session.getTransaction().commit();
        session.close();
 
    }
 
}
package com.kb.dao;

import java.util.Date;

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

import com.kb.model.Employee;
import com.kb.model.Person;

public class DBInteract {
	
	public static void main(String[] args) {
		 
		 //creating configuration object  
	    Configuration cfg=new Configuration();  
	    
	    cfg.configure("hibernate.cfg.xml");//populates the data of the configuration file  
	      
	    //creating seession factory object  
	    SessionFactory factory=cfg.buildSessionFactory();  
	      
        Session session = factory.openSession();
        session.beginTransaction();
 
         
        Person person = new Person("kb", "gc");
        session.save(person);
 
        Employee employee = new Employee("raj", "kumar", "financing", new Date());
        session.save(employee);
         
        session.getTransaction().commit();
        session.close();
 
    }

}

Run it
Output in console

Inheritance2

Table created is only one.
And all our data both parent and child is inserted in the same table.
We can differentiate using only discriminator column. And many columns in parent goes as null.
Inheritance3

will see next types of inheritance strategies in next post.
Thanks for reading and appreciate your comments/feedback.

About the Author

Karibasappa G C (KB)
Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on