In Table Per SubClass Hierarchy there will be the number of classes equals to the number of tables in the database.
If we save the Student class object, hibernate will first save the data related to super class object into the super class related table in the database and then Student object data in Student related table in the database.
Files used in this example

Person.java (Base class)
Student.java (Derived class)
Teacher.java (Derived class)
Inheritance.java (Executing Query helper class)
TestInheritance.java (for our logic)
Person.hbm.xml
hibernate.cfg.xml

Create MySQL tables

person table
hibernate inheritance example

student table
hibernate inheritance example

teacher table
hibernate inheritance example

Person.java

import java.io.Serializable;
public abstract class Person implements Serializable {

    private int id;
    private String name;

    public Person() {
    }

    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;
    }

}

 

Student.java

public class Student extends Person {

    private String year;

    public Student() {
    }

    public String getYear() {
        return year;
    }

    public void setYear(String year) {
        this.year = year;
    }

}

 

Teacher.java

public class Teacher extends Person {

    private String subject;

    public Teacher() {
    }

    public String getSubject() {
        return subject;
    }

    public void setSubject(String subject) {
        this.subject = subject;
    }

}

 

Inheritance.java

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;


public class Inheritance {

    Session session = null;

    public Inheritance() {
        session = HibernateUtil.getSessionFactory().getCurrentSession();
    }

    public void savePerson(Student s, Teacher t) {
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            session.save(s);
            session.save(t);
            tx.commit();
        } catch (HibernateException e) {
            e.printStackTrace();
        }
    }
}

 

TestInheritance.java

public class TestInheritance {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Inheritance ihr = new Inheritance();
        System.out.println("***Testing for Table per SubClass hierarchy***");
        Student s2 = new Student();
        Teacher t2 = new Teacher();
        s2.setId(3);
        s2.setName("Student2");
        s2.setYear("2nd Year");
        t2.setId(4);
        t2.setName("Teacher2");
        t2.setSubject("Maths");
        ihr.savePerson(s2, t2);
        System.out.println("***Testing for Table per SubClass hierarchy***");
    }

}

 

Person.hbm.xml:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="in.sblog.domain.Person" table="person">
        <id name="id" column="id" />
        <property name="name" column="name" />
        <joined-subclass name="in.sblog.domain.Student" table="student">
            <key column="skey"/>
            <property name="year" column="year" length="50" />
        </joined-subclass>
        <joined-subclass name="in.sblog.domain.Teacher" table="teacher">
            <key column="tkey"/>
            <property name="subject" column="subject" length="50" />
        </joined-subclass>
    </class>
</hibernate-mapping>

 

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">
<hibernate-configuration>
  <session-factory>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/cdcol?zeroDateTimeBehavior=convertToNull</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.show_sql">true</property>
    <property name="hibernate.format_sql">true</property>
    <property name="hibernate.current_session_context_class">thread</property>
    <property name="hibernate.query.factory_class">org.hibernate.hql.classic.ClassicQueryTranslatorFactory</property>
    <mapping resource="in/sblog/domain/Person.hbm.xml"/>
  </session-factory>
</hibernate-configuration>

 

In the hibernate mapping file, <key/> tag is there because once we save the derived class object, hibernate will first save the base class object then derived class object. So at the time of saving the derived class object hibernate will copy the primary key value of the base class into the corresponding derived class, see in the above output 3 copied into skey column of student table and 4 copied into tkey column of the teacher table.

Once the data have been successfully saved into the database the output will be:

person table

hibernate inheritance example

student table

hibernate inheritance example

teacher table

hibernate inheritance example

That’s all. Thank your for your patience. Please do not forget to leave a comment.

Tags:

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on Roy Tutorials | TwitterFacebook Google PlusLinkedin | Reddit | Email Me

Leave a Reply

Your email address will not be published. Required fields are marked *