I am going to give explaination and example on hibernate table per class hierarchy, consider we have base class named Person and two derived classesStudent and Teacher

If we save the derived class object like Student or Teacher then automatically Person class object will also be saved into the database, and in the database all the data will be stored into a single table only, which is base class table for sure.

But here we must use one extra discriminator column in the database to identify which derived class object we have  saved in the table along with the base class object. This discriminator column is mandatory otherwise hibernate will throw an exception.
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 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 Class hierarchy***");
        Student s1 = new Student();
        Teacher t1 = new Teacher();
        s1.setId(1);
        s1.setName("Student1");
        s1.setYear("1st Year");
        t1.setId(2);
        t1.setName("Teacher1");
        t1.setSubject("Physics");
        ihr.savePerson(s1, t1);
    }

}

 

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" />
        <discriminator column="discriminator" type="string" length="5"/>
        <property name="name" column="name" />
        <subclass name="in.sblog.domain.Student" discriminator-value="yr">
            <property name="year" column="year" length="4" />
        </subclass>
        <subclass name="in.sblog.domain.Teacher" discriminator-value="sub">
            <property name="subject" column="subject" length="50" />
        </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>

 

Once the data successfully saved into the database

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

Leave a Reply

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