Searching...
Saturday, 17 August 2013

Hibernate Inheritance Table per class hierarchy Example

03:51

Hibernate API supports Inheritance mapping in 3 ways

Table per class hierarchy
Table per subclass
Table per concrete class

Table per class hierarchy

In this example we will see how to implement one Table per class hierarchy. It means for the the hierarchy of of class will have only one table in the background and will have a row for all the fields in the full class hierarchy and  will have a discriminator column to hold type information. Let us consider one parent class as Vehicle and Sub classes like Car and Bus

image

Even we have 3 classes in the front Hibernate will save the data as below in one single table (Table per class hierarchy)
 
image
 
The discriminator column will help to identify the fields belongs to which entity. Let us see how this will implement 

1. Create a Java project

Create a Java project and update Hibernate jars and Mysql driver jar in to build path. (Download Hibernate , MySql Driver)

image

2. Create a Vehicle class

package com.pretech;
 
import javax.persistence.Column;
import javax.persistence.DiscriminatorColumn;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.Table;
import javax.persistence.DiscriminatorType;
 
@Entity
@Table(name = "VEHICLE")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "Discriminator", discriminatorType = DiscriminatorType.STRING)
@DiscriminatorValue(value = "V")
public class Vehicle {
 
    @Id
    @GeneratedValue
    @Column(name = "Vehicle_Id")
    int VehicleId;
 
    @Column(name = "Vehicle_Name")
    String VehicleName;
 
    public Vehicle() {
 
    }
    public Vehicle(String VehicleName) {
        this.VehicleName = VehicleName;
    }
    public int getVehicleId() {
        return VehicleId;
    }
    public void setVehicleId(int vehicleId) {
        VehicleId = vehicleId;
    }
    public String getVehicleName() {
        return VehicleName;
    }
    public void setVehicleName(String vehicleName) {
        VehicleName = vehicleName;
    }
}

In this above class we used below new annotations to implement Table per class hierarchy.

@inheritance- is used to implement inheritance and its strategy (SINGLE_TABLE)

@DiscriminatorColumn-is used to define discriminator column for Single_Table and joined strategy.

@DiscriminatorValue-is used to defines value in discriminator column for that class.

3. Create a sub class (Car.java)

package com.pretech;
 
import javax.persistence.Column;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
 
@Entity
@DiscriminatorValue(value = "C")
public class Car extends Vehicle {
 
    @Column(name = "Car_Model")
    String carmodel;
 
    public Car() {
 
    }
 
    public Car(String vehicleName, String carmodel) {
        super(vehicleName);
        this.carmodel = carmodel;
    }
 
    public String getCarmodel() {
        return carmodel;
    }
 
    public void setCarmodel(String carmodel) {
        this.carmodel = carmodel;
    }
}

4.Create Bus entity (Bus.java)

package com.pretech;
 
import javax.persistence.Column;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
 
@Entity
@DiscriminatorValue(value = "B")
public class Bus extends Vehicle {
 
    @Column(name = "Bus_Model")
    String busmodel;
    public Bus() {
    }
    public Bus(String vehicleName, String busmodel) {
        super(vehicleName);
        this.busmodel = busmodel;
    }
    public String getBusmodel() {
        return busmodel;
    }
    public void setBusmodel(String busmodel) {
        this.busmodel = busmodel;
    }
}

5.Create Hibernate config file(hibernate.cfg.xml)

<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD//EN"
    "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory name="studentFactory">
            <property name="connection.driver_class">
                 com.mysql.jdbc.Driver
            </property>
        <property name="connection.url">
             jdbc:mysql://localhost:3306/hibernateschema
        </property>
        <property name="connection.username">
             root
        </property>
        <property name="connection.password">
            root
        </property>
            <property name="connection.pool_size">5</property>
            <!-- SQL dialect -->
            <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
            <!-- Echo all executed SQL to stdout -->
            <property name="show_sql">true</property>
             <property name="hbm2ddl.auto">update</property>
  <mapping class="com.pretech.Vehicle"></mapping>  
  <mapping class="com.pretech.Bus"></mapping>  
  <mapping class="com.pretech.Car"></mapping>            
    </session-factory>
</hibernate-configuration>

6. Create a main program to Save Vehicles

package com.pretech;
 
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
 
public class VehicleMain {
 
    private static SessionFactory sessionFactory;
 
    public static void main(String[] args) {
 
        try {
            sessionFactory = new Configuration().configure("hibernate.cfg.xml")
                    .buildSessionFactory();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        Session session = sessionFactory.openSession();
 
        Vehicle vehicle = new Vehicle("Four Wheeler");
        Bus bus = new Bus("Bus", "Volvo");
        Car car = new Car("Car", "Honda");
        session.beginTransaction();
        session.save(vehicle);
        session.save(bus);
        session.save(car);
        session.getTransaction().commit();
        System.out.println("Vehicle objects Saved");
 
        if (session != null)
            session.close();
    }
 
}

7. Run it

Once you run the program we will see below output

Hibernate: insert into VEHICLE (Vehicle_Name, Discriminator) values (?, 'V')
Hibernate: insert into VEHICLE (Vehicle_Name, Bus_Model, Discriminator) values (?, ?, 'B')
Hibernate: insert into VEHICLE (Vehicle_Name, Car_Model, Discriminator) values (?, ?, 'C')
Vehicle objects Saved

Database Table output

image

In this table we can see while saving Vehicle object all other instances are null and while saving Bus object Car value and Vehicle values are null. Also Discriminator column is distinguishing each instances.

Download Source Code

Hibernate -One table per class example

References

Hibernate Annotations

0 comments: