Hibernate Polymorphic Queries

In this tutorial you will learn about the HQL polymorphic queries.

Hibernate Polymorphic Queries

Hibernate Polymorphic Queries

In this tutorial you will learn about the HQL polymorphic queries.

Hibernate supports the polymorphic queries. Polymorphic means the polymorphism i.e an object that has a IS-A relation with their own type class object. Hibernate query doesn't only returns the instance of parent class, it returns the instances of subclasses also i.e a query will return all those persistent classes instance which extends that class or an interface is implemented.

Example :

An example is being given will demonstrate you about the HQL polymorphic query. In this example you will see a child class extends the parent class by which all the features of parent class will be inherited by the child class. Here I will use a single table to fetch the data. So to fetch the data from table we would be not need to mapped the both classes only the child class mapping in .hbm.xml file with parent data members is sufficient. When you will fetch the data using the HQL query, data members of parent classes can be accessed by the child class. In the example given below you can see that the data members empId, name are the data members of Employee.java class whereas the data member salary is of the class Salary.java. But when a query is executed the Salary class object accessed the Employee class data members.

Salary table

CREATE TABLE `salary` ( 
`empId` int(10) NOT NULL, 
`name` varchar(15) default NULL, 
`address` varchar(15) default NULL, 
`salary` longblob, 
PRIMARY KEY (`empId`) 
)

Employee.java

package roseindia;

public class Employee
{
private int empId;
private String name;
private String address;
private int number;

public Employee()
{

}
public Employee(String name, String address, int number)
{
this.name = name;
this.address = address;
this.number = number;
}

public int getEmpId() {
return empId;
}

public void setEmpId(int empId) {
this.empId = empId;
}

public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}

}

Salary.java

package roseindia;

public class Salary extends Employee
{
private long salary;
public Salary()
{

}
public Salary(String name, String address, int number, long
salary, int empId)
{
super(name, address, number);
setSalary(salary);
}

public long getSalary()
{
return salary;
}
public void setSalary(long newSalary)
{
newSalary = salary;
} 
}

PolymorphicQuery.hbm.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate mapping DTD//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="roseindia">
<class name="Salary" table="salary">
<id name="empId" type="int" column="empId">
<generator class="assigned"/>
</id>
<property name="name">
<column name="name"/>
</property>
<property name="address">
<column name="address"/>
</property>
<property name="number" type="int">
<column name="number"/>
</property>
<property name="salary" type="long">
<column name="salary"/>
</property>
</class>

</hibernate-mapping>

hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://192.168.10.13:3306/data
</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.connection.pool_size">10</property>
<property name="show_sql">true</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.current_session_context_class">thread</property>
</session-factory>

</hibernate-configuration>

HibernatePolymorphicQueries.java

package roseindia;

import java.util.Iterator;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class HibernatePolymorphicQueries {
private static SessionFactory sessionFactory;
private static ServiceRegistry serviceRegistry;

public static void main(String args[])
{
Session session = null;
try
{
try
{
Configuration cfg= new Configuration().addResource("roseindia/PolymorphicQuery.hbm.xml");
cfg.configure();
serviceRegistry = new ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry();
sessionFactory = cfg.buildSessionFactory(serviceRegistry);
}
catch(Throwable th)
{
System.err.println("Failed to create sessionFactory object."
+ th);
throw new ExceptionInInitializerError(th);
}
session = sessionFactory.openSession();
Query query = session.createQuery("select s.empId, s.name, s.salary from Salary s ");
Iterator sal = query.iterate();
System.out.println("EmpId \t Name \t Salary");
while(sal.hasNext())
{
Object[] obj = (Object[]) sal.next();
System.out.println(obj[0]+" \t "+ obj[1]+ " \t "+ obj[2]);

}
}
catch(Exception e)
{
System.out.println(e.getMessage());
} 
finally
{
session.close();
}
}
}

Output :

1. Salary Table is as :

2. When you will execute the HibernatePolymorphicQueries.java ( RightClick -> RunAs -> Java Application ) you will get the output as :

INFO: HHH000397: Using ASTQueryTranslatorFactory
Hibernate: select salary0_.empId as col_0_0_, salary0_.name as col_1_0_, salary0_.salary as col_2_0_ from salary salary0_

Download Source Code