Searching...
Saturday, 17 August 2013

Hibernate Inheritance Table per Concrete class example using Annotations

21:06

Hibernate API supports Inheritance mapping in 3 ways

Table per class hierarchy
Table per subclass
Table per concrete class

Table per Concrete class

In this example we will see how to implement one Table per Concrete class , it means each concrete class is mapped as normal persistent class and mapping of the subclass repeats the properties of the parent class.

Let us consider Vehicle as parent class and Bus, Car are the subclasses, as per Table per concrete class three table will create and in the sub class table will get the properties of the super class Vehicle.

[image%255B3%255D.png]

Final table structure (Each sub table will have the properties of parent class e.g.: Vehicle Type)

imageimage

image

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 Vehicle class (Vehicle.java)

package com.pretech;
 
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.Table;
 
@Entity
@Table(name = "VEHICLE")
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class Vehicle {
 
    @Id
    @GeneratedValue(strategy = GenerationType.TABLE)  
    @Column(name = "Vehicle_Id")
    int vehicleId;
 
    @Column(name = "Vehicle_Type")
    String vehicleType;
    public Vehicle(String vehicleType)
    {
        this.vehicleType=vehicleType;
    }
    public int getVehicleId() {
        return vehicleId;
    }
    public void setVehicleId(int vehicleId) {
        this.vehicleId = vehicleId;
    }
    public String getVehicleType() {
        return vehicleType;
    }
    public void setVehicleType(String vehicleType) {
        this.vehicleType = vehicleType;
    }
    public Vehicle() {
    }
 
}

3. Create Bus.java (Sub class)

package com.pretech;
 
import javax.persistence.AttributeOverrides;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.AttributeOverride;
 
@Entity
@Table(name="BUS")  
@AttributeOverrides({
    @AttributeOverride(name="vehicleId", column=@Column(name="Vehicle_Id")),
    @AttributeOverride(name="vehicleName", column=@Column(name="Vehicle_Name"))
 
})
public class Bus extends Vehicle {
 
    @Column(name = "Bus_Model")
    String busmodel;
    @Column(name="Vehicle_name")
    String vehiclename;
    public Bus() {
    }
    public Bus(String vehicleType,String vehicleName, String busmodel) {
        super(vehicleType);
        this.busmodel = busmodel;
        this.vehiclename = vehicleName;
 
    }
    public String getBusmodel() {
        return busmodel;
    }
    public void setBusmodel(String busmodel) {
        this.busmodel = busmodel;
    }
    public String getVehiclename() {
        return vehiclename;
    }
    public void setVehiclename(String vehiclename) {
        this.vehiclename = vehiclename;
    }
 
}

4. Create Car.java (Sub class)

package com.pretech;
 
import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
 
@Entity
@Table(name="CAR")  
@AttributeOverrides({
    @AttributeOverride(name="vehicleId", column=@Column(name="Vehicle_Id")),
    @AttributeOverride(name="vehicleName", column=@Column(name="Vehicle_Name"))
 
})
public class Car extends Vehicle {
 
    @Column(name = "Car_Model")
    String carmodel;
    @Column(name="Vehicle_name")
    String vehiclename;
   
    public Car() {
 
    }
 
    public Car(String vehicleType,String vehicleName, String carmodel) {
        super(vehicleType);
        this.carmodel = carmodel;
        this.vehiclename = vehicleName;
 
    }
    public String getCarmodel() {
        return carmodel;
    }
    public void setCarmodel(String carmodel) {
        this.carmodel = carmodel;
    }
    public String getVehiclename() {
        return vehiclename;
    }
    public void setVehiclename(String vehiclename) {
        this.vehiclename = vehiclename;
    }
}

In the above two sub classes we used two additional annotations ie @AttributeOverrides annotation is used to override mappings of multiple properties or fields and  @AttributeOverride annotation is used to override the mapping of property.

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 Main class

Create a main class to create and save Vehicle objects.

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("Four Wheeler","Bus", "Volvo");
        Car car = new Car("Four Wheeler","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();
    }
 
}

Note that these classes are persisted in different tables and parent attributes are repeated in all tables.

Output

Hibernate: insert into VEHICLE (Vehicle_Type, Vehicle_Id) values (?, ?)
Hibernate: insert into BUS (Vehicle_Type, Bus_Model, Vehicle_name, Vehicle_Id) values (?, ?, ?, ?)
Hibernate: insert into CAR (Vehicle_Type, Car_Model, Vehicle_name, Vehicle_Id) values (?, ?, ?, ?)
Vehicle objects Saved

image

image

image 

Download Source code

Hibernate Table per concrete class example

0 comments: