Friday, December 4, 2015

Hibernate HQL Command execution ways

Selecting Complete Object

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 the type of POJO class

Example
Query qry = session.createQuery("--- HQL command ---");
List objList = qry.list();
Iterator iterator = objList.iterator();
while(i iterator.hasNext())
{
        Object obj = iterator.next();
         Entity entityObj = (Entity)obj;
           /* ……. further code ….. */
}


Selecting Partial Object with More than one Column

In this approach we are going to select partial object, (selected columns, i mean more than
one 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 :
Query qry = session.createQuery("select e.id,e.name from Entity e");
List dataList =qry.list();
Iterator iterator = dataList.iterator();
while(iterator.hasNext())
{
      Object obj[] = (Object obj[])iterator.next();
         System.out.println("-------");
}


Selecting Partial Object with single column

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
Query qry = session.createQuery("select e.id from Entity e");
List dataList =qry.list();
Iterator iterator = dataList.iterator();
while(iterator.hasNext())
{
Integer id = (Integer)it.next();
System.out.println(id.intValue());
}



No comments:

Post a Comment