Showing posts with label Hibernate. Show all posts
Showing posts with label Hibernate. Show all posts

Hibernate Native SQL

Hibernate supports native SQL queries as well, in the below code snippet we will see how to use Native SQL in hibernate. Since Hibernate 3.x offers you to specify handwritten SQL, including stored procedures, for all create, update, delete, and load operations.

Session objects createSQLQuery(“Query”) method is using to get SQLQuery object. We can make use of this either as Scalar query or entity query. 

SQLQuery query = session.createSQLQuery("select * from student")
                .addEntity(Student.class);
        List list = query.list();
        Iterator it = list.iterator();
        while (it.hasNext()) {
            Student stud = (Student) it.next();
            System.out.println(stud.getName());
            System.out.println(stud.getStandard());
        }
 
        System.out.println("Executing Select Scalar Query");
 
        SQLQuery query1 = session.createSQLQuery("select name,standard from student");
        query1.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
        List list1 = query1.list();
 
        for (Object object : list1) {
            Map row = (Map) object;
            System.out.println("name: " + row.get("name"));
            System.out.println("standard:" + row.get("standard"));
        }
 

Reference

http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/querysql.html

Hibernate Inheritance Table per Concrete class example using Annotations

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

Hibernate Inheritance Table per Sub class example using Annotations

Hibernate API supports Inheritance mapping in 3 ways

Table per class hierarchy
Table per subclass
Table per concrete class

Table per sub class

In this example we will see how to implement one Table per sub class . It means each class persist the data in its own separate table but a foreign key relationship exists between the subclass tables and super class table and common data will store in to the parent class

Let us Consider Vehicle is root class and Bus and Car are sub classes. Vehicle id will be as foreign key in Bus and Car table and common data is stored in VEHICLE table and subclass specific fields are stored in BUS and CAR tables.

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 a Vehicle class

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.JOINED)
public class Vehicle {
 
    @Id
    @GeneratedValue(strategy = GenerationType.TABLE)  
    @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;
    }
}

3. Create a sub class (Car.java)

package com.pretech;
 
import javax.persistence.Column;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.Table;
 
@Entity
@Table(name="CAR")  
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;
import javax.persistence.Table;
 
@Entity
@Table(name="BUS")  
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, Vehicle_Id) values (?, ?)
Hibernate: insert into VEHICLE (Vehicle_Name, Vehicle_Id) values (?, ?)
Hibernate: insert into BUS (Bus_Model, Vehicle_Id) values (?, ?)
Hibernate: insert into VEHICLE (Vehicle_Name, Vehicle_Id) values (?, ?)
Hibernate: insert into CAR (Car_Model, Vehicle_Id) values (?, ?)
Vehicle objects Saved

Database Table output

image

image

image 

Download Source Code

Hibernate Inheritance Table per sub class Example

References

Hibernate Annotations

Hibernate Inheritance Table per class hierarchy Example

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

Confusion Matrix + Precision/Recall (Super Simple, With Examples)

  Confusion Matrix + Precision/Recall (Super Simple, With Examples) 1) Binary Classification Setup Binary classification means the model p...

Featured Posts