Hibernate Polymorphic Queries

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


 

Ads

Tutorials   
How to write hello world example program in Hibernate? How to create one to one relationship in Hibernate 4 with Annotation? How to calculate minimum in Hibernate using the min() Function Hibernate 4.3.4 Released: Hibernate 4.3.4.Final Maven dependency Hibernate 4.3 Hello World: Example How to create SessionFactory in Hibernate 4.3.1? Hibernate 4 Hello World: Example of Hello World program Hibernate 4 create Session Factory: Example of creating Session Factory in Hibernate 4 Hibernate 4.3 and JPA 2.1 Example What is Hibernate in Java? Hibernate Overview and Architecture What is JPA 2.1? Hibernate 4.3.0.Final Maven dependency Hibernate 4.3 ORM Features Hibernate 4.3 Tutorial Hibernate Criteria average example Hibernate Criteria load all objects from table Hibernate Criteria Hibernate beginner tutorial Hibernate Session.delete() Example Hibernate save or update method example Hibernate Load Example Hibernate save Example - Rose India Hibernate 4 tutorials Hibernate Example Step by Step in Eclipse Hibernate Configuration files Setup Hibernate Environment Hibernate Architecture Hibernate Overview Hibernate 4.2 Tutorial Hibernate 4 Annotations Tutorial Hibernate 4 AnnotationSessionFactoryBean hibernate versions hibernate jndi hibernate tomcat hibernate metamodel generator hibernate entity Seam Hibernate C3P0 Hibernate hibernate shard hibernate means temporal hibernate jsf hibernate spring j2ee hibernate spring hibernate encrypted password alias_to_entity_map hibernate temporal jsf spring hibernate hibernate by example hibernate repository hibernate sample code
Ads

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

Advertisements

Share on Google+Share on Google+

Hibernate Polymorphic Queries

Posted on: March 13, 2012 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Advertisements

 

Discuss: Hibernate Polymorphic Queries  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:0

Ads

 

Ads