Table per Hierarchy using Annotations (Single Table)
We have already seen an example for Table per hierarchy (here). In this article we are going to see how Table per Hierarchy can be implemented in Hibernate using Annotations.

pic1

In this diagram, Employee is a class and Mobile and LandLine classes extends employee class. When we insert the values in them and when we run, all the data will be accumulated in a Single table. This is known as Table per Hierarchy.

Lets see this example in Detail,

Structure
structure

employee.java

package com.javainfinite.pojo;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.Table;

@Entity
@Table(name="Annotate_Employee")
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)//Optional - SINGLE_TABLE is default strategy
public class employee {
    @Id
    @GeneratedValue
    private int id;
    private String ename;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getEname() {
        return ename;
    }

    public void setEname(String ename) {
        this.ename = ename;
    } 
}

mobile.java

package com.javainfinite.pojo;

import javax.persistence.Entity;

@Entity
public class mobile extends employee{
    
    private String tnumber;

    public String getTnumber() {
        return tnumber;
    }

    public void setTnumber(String tnumber) {
        this.tnumber = tnumber;
    }
    
}

landline.java

package com.javainfinite.pojo;

import javax.persistence.Entity;

@Entity
public class landline extends employee {
    
    private String tnumber;

    public String getTnumber() {
        return tnumber;
    }

    public void setTnumber(String tnumber) {
        this.tnumber = tnumber;
    }
}

NewHibernateUtil.java

package com.javainfinite.pojo;

import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.SessionFactory;


public class NewHibernateUtil {

    private static final SessionFactory sessionFactory;
    
    static {
        try {
            // Create the SessionFactory from standard (hibernate.cfg.xml) 
            // config file.
            sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            // Log the exception. 
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }
    
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}

hibernate.cfg.xml

<hibernate-configuration>
  <session-factory>
    <property name="hibernate.hbm2ddl.auto">create</property>  
    <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">URL</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password">root</property>
    <property name="hibernate.show_sql">true</property>
    <mapping class="com.javainfinite.pojo.employee"/>
    <mapping class="com.javainfinite.pojo.landline"/>
    <mapping class="com.javainfinite.pojo.mobile"/>
  </session-factory>
</hibernate-configuration>

execution.java

package com.javainfinite.execute;

import com.javainfinite.pojo.NewHibernateUtil;
import com.javainfinite.pojo.employee;
import com.javainfinite.pojo.landline;
import com.javainfinite.pojo.mobile;
import org.hibernate.Session;
import org.hibernate.Transaction;


public class execution {
    
    public static void main(String args[])
    {
        
        employee emp=new employee();
        mobile mob=new mobile();
        landline land=new landline();
        
        
        Session session=NewHibernateUtil.getSessionFactory().openSession();
        
        try
        {
            Transaction trans=session.beginTransaction();
            emp.setEname("Alpha");
            
            mob.setEname("Mobile Alpha");
            mob.setTnumber("Mob: 23432");
            
            land.setEname("LandLine Alpha");
            land.setTnumber("LandLine: 22343");
            
            session.save(emp);
            session.save(mob);
            session.save(land);
            session.close();
            trans.commit();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
    
}

 

Output:
op1

From the output we can see that, we have used @Entity annotation in both mobile and landline classes but hibernate has created only one table Annotate_Employee and has inserted both the values of mobile and landline in single table

op2

There is one column – DTYPE that differentiates the classes and the data

 

 

 

 

By Sri

One thought on “Table per Hierarchy using Annotations (Single Table)”

Leave a Reply

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