Different Ways Of Executing HQL Commands

We can execute our HQL command in 3 ways,  like by selecting total object, partial object (more than one column), partial object (with single column).  Let us see..

  • In this approach, we are going to select complete object from the database, so while iterating the collection, we need to typecast each object into our  POJO class type only
  • Internally hibernate converts each row selected from the table into an object of POJO class and hibernate stores all these POJO class objects into list so while iterating the collection, we typecast into POJO class type

Example:

123456789Query qry = session.createQuery("-- our HQL command --");
List l =qry.list();
Iterator it = l.iterator();
while(it.hasNext())
{
   Object o = it.next();
   Project p = (Product)o;
   ----- ------- ------
}

 

Case 2: [ Selecting Partial Object ]

  • In this approach we are going to select partial object, (selected columns, i mean more than one column not single column)
  • In this case hibernate internally stores the multiple column values of each row into an object array and stores these object arrays into List collection
  • At the time of iterating the collection, we need to typecast the result into an object arrays

Example:

123456789Query qry = session.createQuery("select p.pid,p.pname from Product p");
List l =qry.list();
Iterator it = l.iterator();
while(it.hasNext())
{
   Object o[] = (Object o[])it.next();
   System.out.println("-------");
   ----- ------- ------
}

Case 3: [ Selecting Partial Object ]

  • In this case we are going to select partial object with single column from the database
  • In this case hibernate internally creates an object of that value type and stores all these objects into the list collection
  • At the time of iterating the collection, we need to typecast into that object type only

Example:

123456789Query qry = session.createQuery("select p.pid from Product p");
List l =qry.list();
Iterator it = l.iterator();
while(it.hasNext())
{
   Integer i = (Integer)it.next();
   System.out.println(i.intValue());
   ----- ------- ------
}

Note:  it.next() return type is always Object.

Related Articles

post a comment