Hibernate Criteria setResultTransformer


Problem: How to loop through a resultset with the column alias names defined in the native SQL, instead of accessing the resultset by column index in hibernate

Solution:

Sometimes, accessing the resultset by the names of the columns is much convenient than accessing the result set by index, say a row’s first column as get(0) and second column by get(1).

In this case, when using hibernate, calling setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP).list(),  causes it to return a list of Maps.

For example,

Query query1 = session.createSQLQuery(query.toString()).setParameter(“PRODID”, prodid).setParameter(“PRODTYPE”, prodtype);

//Convert the Query object to a list of maps

List iter1 = query1.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP).list();
Map<String,Object> map= new HashMap<String,Object>();
for (Object object : iter1)
{
map= (Map<String,Object>)object;

logger.debug(map.get(“PRODID”));

logger.debug(map.get(“PRODTYPE”));

logger.debug(map.get(“PRODEXP”));

logger.debug(map.get(“PRODCOST”));

}

  1. #1 by Imran Latif on July 20, 2012 - 9:34 am

    It works

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: