Ashu-Goel
Ashu-Goel

Reputation: 31

Get Column Name By Hibernate Query

Query query = this.getSession().createSQLQuery(sqlQuery);       
query.setResultTransformer(new AliasToEntityMapResultTransformer());

List results = query.list();

In above code, results contains elements of Map and I am able to get the column name by key of Map but as you know query.list() returns the elements of HashMap thats why the ordering of column name not in sequence and I want the column name odering baseed on sql-query sequence.

Upvotes: 1

Views: 2809

Answers (2)

Mankix
Mankix

Reputation: 21

This is a very old question, but it is a bit vexing as to why there isn't something like this in the transformers already.

Running the query with the transformer:

Query sqlQuery = session.createSQLQuery(sqlStatement);
sqlQuery.setResultTransformer(AliasToEntityLinkedMapResultTransformer.INSTANCE);

List results = query.list();

For the transformer, I extended BasicTransformerAdapter as opposed to AliasToEntityMapResultTransformer.

import org.hibernate.transform.BasicTransformerAdapter

public class AliasToEntityLinkedMapResultTransformer extends BasicTransformerAdapter implements Serializable {
    public static final AliasToEntityLinkedMapResultTransformer INSTANCE = new AliasToEntityLinkedMapResultTransformer();

    private AliasToEntityLinkedMapResultTransformer() {

    }

    public Object transformTuple(Object[] tuple, String[] aliases) {
        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;
    }

    private Object readResolve() {
        return INSTANCE
    }

    public boolean equals(Object other) {
        return other != null && AliasToEntityLinkedMapResultTransformer.class.isInstance(other)
    }

    public int hashCode() {
        return getClass().getName().hashCode()
    }
}

Nothing revolutionary or straightforward, but there it is.

Upvotes: 2

JB Nizet
JB Nizet

Reputation: 692121

Implement your own AliasToEntityLinkedMapResultTransformer, by using the code of AliasToEntityMapResultTransformer as an example, but using a LinkedHashMap instead of a HashMap. LinkedHashMap preserves insertion order.

Upvotes: 1

Related Questions