Tuesday, April 15, 2014

Hibernate : Using ResultTransformer

If we want to get the column name in hibernate for a table with results then we use setResultTransformer() and pass AliasedTupleSubsetResultTransformer.
For some reason if want to see the column name in same order the way it is with create table then we need to have our own AliasedTupleSubsetResultTransformer. We can define our own class which will extend AliasedTupleSubsetResultTransformer and we can override behaviour to use LinkedHashMap to get the columns in order.

Example:

public class AliasToEntityOrderedMapResultTransformer extends AliasedTupleSubsetResultTransformer {

public static final AliasToEntityOrderedMapResultTransformer INSTANCE = new AliasToEntityOrderedMapResultTransformer();

/**
 * Disallow instantiation of AliasToEntityOrderedMapResultTransformer .
 */
private AliasToEntityOrderedMapResultTransformer () {
}

/**
 * {@inheritDoc}
 */
public Object transformTuple(Object[] tuple, String[] aliases) {
//linkedhashmap to get table column name in order        
    Map result = new LinkedHashMap(tuple.length);
    for ( int i=0; i<tuple.length; i++ ) {
        String alias = aliases[i];
        if ( alias!=null ) {
            result.put( alias, tuple[i] );
        }
    }
    return result;
}

/**
 * {@inheritDoc}
 */
public boolean isTransformedValueATupleElement(String[] aliases, int tupleLength) {
    return false;
}

/**
 * Serialization hook for ensuring singleton uniqueing.
 *
 * @return The singleton instance : {@link #INSTANCE}
 */
private Object readResolve() {
    return INSTANCE;
}
}


Using the custom implementation - AliasedTupleSubsetResultTransformer 

     Session session = sessionFactory.getCurrentSession();
        String queryStr = "select * from EMPLOYEE;
        Query query = session.createSQLQuery(queryStr);
//set the custom implementation
        query.setResultTransformer(AliasToEntityOrderedMapResultTransformer.INSTANCE);
//get the ordered column name and value
        List<Map<String,Object>> aliasToValueMapList = query.list();