Map Result Transformer
The following example shows how to use map result transformer.
Refer first example for the configuration and mapping.
package com.bethecoder.tutorials.hibernate.basic.tests;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.transform.Transformers;
import com.bethecoder.tutorials.hibernate.basic.util.HibernateUtil;
public class HQLTransformAliasMapTest {
/**
* @param args
*/
public static void main ( String [] args ) {
Session session = HibernateUtil.getSessionFactory () .openSession () ;
session.beginTransaction () ;
String HQL_QUERY = "select comp.id as comp_id, comp.name as comp_name from Company comp" ;
Query query = session.createQuery ( HQL_QUERY ) ;
query.setResultTransformer ( Transformers.ALIAS_TO_ENTITY_MAP ) ;
List<?> rows = query.list () ;
System.out.println ( "Selected row count : " + rows.size ()) ;
for ( Object row : rows ) {
System.out.println ( row ) ; //Each row is a map of properties in the query
//with key as alias and property as value
}
session.getTransaction () .commit () ;
session.close () ;
}
}
It gives the following output,
Selected row count : 10
{comp_id=1, comp_name=PQR}
{comp_id=2, comp_name=ABC}
{comp_id=3, comp_name=MNO}
{comp_id=4, comp_name=IJK}
{comp_id=5, comp_name=ART}
{comp_id=6, comp_name=RNK}
{comp_id=7, comp_name=AOQ}
{comp_id=8, comp_name=BQO}
{comp_id=9, comp_name=CFR}
{comp_id=10, comp_name=CFR}