Inheritance in Hibernate -> Table per concrete class

lets start with the below code(for explanations on Hibernate inheritance see previous post)

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)Person.java

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
 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)Employee.java

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)Owner.java

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 Owner extends Person {
    private Long ProfitAmt;
    private Long InvestedAmt;
    
     public Owner(String firstName, String lastName,Long ProfitAmt,
             Long InvestedAmt) {
        super(firstName, lastName);
        this.ProfitAmt=ProfitAmt;
        this.InvestedAmt=InvestedAmt;
    }
 
    public Long getProfitAmt() {
        return ProfitAmt;
    }
 
    public void setProfitAmt(Long profitAmt) {
        ProfitAmt = profitAmt;
    }
 
    public Long getInvestedAmt() {
        return InvestedAmt;
    }
 
    public void setInvestedAmt(Long investedAmt) {
        InvestedAmt = investedAmt;
    }
 
 
}
package com.kb.model;

public class Owner extends Person {
	private Long ProfitAmt;
    private Long InvestedAmt;
	
	 public Owner(String firstName, String lastName,Long ProfitAmt,
			 Long InvestedAmt) {
		super(firstName, lastName);
		this.ProfitAmt=ProfitAmt;
		this.InvestedAmt=InvestedAmt;
	}

	public Long getProfitAmt() {
		return ProfitAmt;
	}

	public void setProfitAmt(Long profitAmt) {
		ProfitAmt = profitAmt;
	}

	public Long getInvestedAmt() {
		return InvestedAmt;
	}

	public void setInvestedAmt(Long investedAmt) {
		InvestedAmt = investedAmt;
	}


}

5)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
24
25
26
<?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">
        <id name="personId" column="PERSON_ID">
            <generator class="assigned" />
        </id>
 
        <property name="firstName" />
        <property name="lastName" column="lastname" />
 
        <union-subclass name="Employee" table="EMPLOYEETC">
                <property name="departmentName" column="department_name" />
                <property name="joiningDate" type="date" column="joining_date" />
        </union-subclass>
        
        <union-subclass name="Owner" table="OwnerTC">
                <property name="ProfitAmt" column="ProfitAmt" />
                <property name="InvestedAmt" column="InvestedAmt" />
        </union-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">
        <id name="personId" column="PERSON_ID">
            <generator class="assigned" />
        </id>
 
        <property name="firstName" />
        <property name="lastName" column="lastname" />
 
        <union-subclass name="Employee" table="EMPLOYEETC">
                <property name="departmentName" column="department_name" />
                <property name="joiningDate" type="date" column="joining_date" />
        </union-subclass>
        
        <union-subclass name="Owner" table="OwnerTC">
                <property name="ProfitAmt" column="ProfitAmt" />
                <property name="InvestedAmt" column="InvestedAmt" />
        </union-subclass> 
</class>
</hibernate-mapping>

6)Client code

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
40
41
42
43
44
45
46
47
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.Owner;
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("kbTC", "gc");
        session.save(person);
        person.setPersonId(0);
 
       Employee employee = new Employee("rajTC", "kumar", "financing", new Date());
        employee.setPersonId(2);
        session.save(employee);
         
       Owner owner = new Owner("raviTC", "chandra", 10000l, 50000l);
       owner.setPersonId(3);
        session.save(owner);
       
        
     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.Owner;
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("kbTC", "gc");
        session.save(person);
        person.setPersonId(0);
 
       Employee employee = new Employee("rajTC", "kumar", "financing", new Date());
        employee.setPersonId(2);
        session.save(employee);
         
       Owner owner = new Owner("raviTC", "chandra", 10000l, 50000l);
       owner.setPersonId(3);
        session.save(owner);
       
        
     session.getTransaction().commit();
        session.close();
 
    }

}

Run it and see the output
OutpuConsole

Tables created are

TablesCreated

Data Created as below

DataCreated

See here the first name last name and person id is getting repeated in both the children owner and employee. This duplication of columns in each child can be avoided in the next strategy.

Note : We can’t give auto assignment of id in this kind of strategy. We have to explicitly give the id value.

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