Monday, April 25, 2016

Inheritance in Hibernate & Example 3

Inheritance in Hibernate and different strategies

By default hibernate follows Single table Strategy i.e. Single table for all Parent and Sub Classes.
Additionally hibernate includes dtype i.e discriminator type to distinguish row types of single table created.

Vehicle.java

@Entity
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="VEHILCE_TYPE",
discriminatorType=DiscriminatorType.STRING)
public class Vehicle {

      @Id
      @GeneratedValue(strategy=GenerationType.AUTO)
      @Column(name="VEHICLE_ID")
      private int vehicleId;
     
      @Column(name="VEHILCE_NAME")
      private String vehicleName;
      public int getVehicleId() {
            return vehicleId;
      }
      public void setVehicleId(int vehicleId) {
            this.vehicleId = vehicleId;
      }
      public String getVehicleName() {
            return vehicleName;
      }
      public void setVehicleName(String vehicleName) {
            this.vehicleName = vehicleName;
      }
}

TwoWheeler.java

@Entity
@DiscriminatorValue("Bike")
public class TwoWheeler extends Vehicle {

     private String steeringHandle;

     public String getSteeringHandle() {
           return steeringHandle;
     }

     public void setSteeringHandle(String steeringHandle) {
           this.steeringHandle = steeringHandle;
     }
    
    
}


FourWheeler.java

@Entity
@DiscriminatorValue("Car")
public class FourWheeler extends Vehicle {

     private String steeringWheeler;

     public String getSteeringWheeler() {
           return steeringWheeler;
     }

     public void setSteeringWheeler(String steeringWheeler) {
           this.steeringWheeler = steeringWheeler;
     }
}

HibernateTest.java

public class HibernateTest {

     public static void main(String[] args) {

           Vehicle vehicle = new Vehicle();
           vehicle.setVehicleName("Aeroplane");
          
           TwoWheeler twoWheeler = new TwoWheeler();
           twoWheeler.setVehicleName("R15");
           twoWheeler.setSteeringHandle("Yamaha Steering Handle");
          
           FourWheeler fourWheeler = new FourWheeler();
           fourWheeler.setVehicleName("Hyundai Creta");
           fourWheeler.setSteeringWheeler("Hyundai Steering Wheel");
          
           SessionFactory sessionFactory = new                                     Configuration().configure().buildSessionFactory();
           Session session = sessionFactory.openSession();
           session.beginTransaction();
           session.save(vehicle);
           session.save(twoWheeler);
           session.save(fourWheeler);
          
           session.getTransaction().commit();
           session.close();
           System.out.println("WOrking till now");
     }
}

hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>

<hibernate-configuration>

    <session-factory>

                                                                                <property 
name="connection.driver_class">org.postgresql.Driver</property>
        <property name="connection.url">jdbc:postgresql://localhost:5432/hibernatedb</property>
        <property name="connection.username">postgres</property>
        <property name="connection.password">password</property>

        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>

        <!-- SQL dialect -->
        <property name="dialect">
            org.hibernate.dialect.PostgreSQLDialect
        </property>

        <!-- Enable Hibernate's automatic session context management -->
        <property name="hbm2ddl.auto">create</property>
        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>
           
            <mapping class="org.javadsalgo.dto.UserDetailsDTO"/>
            <mapping class="org.javadsalgo.dto.Vehicle"/>
            <mapping class="org.javadsalgo.dto.TwoWheeler"/>
            <mapping class="org.javadsalgo.dto.FourWheeler"/>
    </session-factory>

</hibernate-configuration>

Output :

Hibernate: select nextval ('hibernate_sequence')
Hibernate: select nextval ('hibernate_sequence')
Hibernate: select nextval ('hibernate_sequence')
Hibernate: insert into Vehicle (VEHILCE_NAME, VEHILCE_TYPE, VEHICLE_ID) values (?, 'Vehicle', ?)
Hibernate: insert into Vehicle (VEHILCE_NAME, STEERING_HANDLE, VEHILCE_TYPE, VEHICLE_ID) values (?, ?, 'Bike', ?)
Hibernate: insert into Vehicle (VEHILCE_NAME, STEERING_WHEELER, VEHILCE_TYPE, VEHICLE_ID) values (?, ?, 'Car', ?)
WOrking till now

Sql > Select * from Vehicle


b) TABLE_PER_CLASS STRATEGY 

* No role of discriminator as every Entity has different Table
* No null values in table as in case of Single_Table_Per class strategy.
* It duplicates properties of parent class.
* More normalized than Single Table per Class strategy.

On changing @Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)

Output :

Hibernate: select hibernate_sequence.nextval from dual
Hibernate: select hibernate_sequence.nextval from dual
Hibernate: select hibernate_sequence.nextval from dual
Hibernate: select hibernate_sequence.nextval from dual
Hibernate: insert into USER_DETAILS (createdOn, description, USER_NAME, VEHICLE_ID, USER_ID) values (?, ?, ?, ?, ?)
Hibernate: insert into Vehicle (VEHILCE_NAME, VEHICLE_ID) values (?, ?)
Hibernate: insert into TwoWheeler (VEHILCE_NAME, STEERING_HANDLE, VEHICLE_ID) values (?, ?, ?)

Hibernate: insert into FourWheeler (VEHILCE_NAME, STEERING_WHEELER, VEHICLE_ID) values (?, ?, ?)

SQL > select * from Vehicle

VEHICLE_ID|VEHILCE_NAME

2|Aeroplane

SQL > select * from TwoWheeler

VEHICLE_ID|VEHILCE_NAME|STEERING_HANDLE

3|R15|Yamaha Steering Handle

SQL > select * from FourWheeler

VEHICLE_ID|VEHILCE_NAME|STEERING_WHEELER

4|Hyundai Creta|Hyudai Steering Wheel



c) JOIN Table Strategy

* More normalized form than other table strategies.
* Not duplicating properties of the parent class.
* Vehicle ID is mapped between parent and child.

On changing @Inheritance(strategy=InheritanceType.JOINED)

Output :

Hibernate: select hibernate_sequence.nextval from dual
Hibernate: select hibernate_sequence.nextval from dual
Hibernate: select hibernate_sequence.nextval from dual
Hibernate: select hibernate_sequence.nextval from dual
Hibernate: insert into USER_DETAILS (createdOn, description, USER_NAME, VEHICLE_ID, USER_ID) values (?, ?, ?, ?, ?)
Hibernate: insert into Vehicle (VEHILCE_NAME, VEHICLE_ID) values (?, ?)
Hibernate: insert into Vehicle (VEHILCE_NAME, VEHICLE_ID) values (?, ?)
Hibernate: insert into TwoWheeler (STEERING_HANDLE, VEHICLE_ID) values (?, ?)
Hibernate: insert into Vehicle (VEHILCE_NAME, VEHICLE_ID) values (?, ?)

Hibernate: insert into FourWheeler (STEERING_WHEELER, VEHICLE_ID) values (?, ?)

SQL > select * from Vehicle

VEHICLE_ID|VEHILCE_NAME
2|Aeroplace
3|R15

4|Hyundai Creta

SQL > select * from TwoWheeler


STEERING_HANDLE|VEHICLE_ID

Yamaha Steering Handle|3

SQL > select * from FourWheeler

STEERING_WHEELER|VEHICLE_ID
Hyudai Steering Wheel|4


No comments:

Post a Comment