salar
salar

Reputation: 13

HQL query returns a map which does not have the same order as specified in the query

I am executing an HQL query like this: (hql query will be dynamic with difrent column names , no of columns , data types )

Session session = getSession();
Query hqlQuery = session.createQuery("select a.id as Id, a.name as Name, a.description as Description, a.locationCountryId as LocationCountryId  from AboutUsMaster as a");
hqlQuery.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
List<Map<String, String>> myMapList =  hqlQuery.list();
for (Map<String, String> map : myMapList ){
        System.out.println(map.toString());
}

Output:

{Name=Test About, LocationCountryId=1, Description=Description, Id=9}

In the map I want to get the same order as I'm selecting in the query. In the query I select id, name , description , locationCountryId but in the map I get entries in a different order.

So how to get the same order as specified in the query?

Upvotes: 1

Views: 1021

Answers (2)

Lathy
Lathy

Reputation: 887

There is no guarantee of order in map.

Refer: Link

Please allow me to modify your code,

for (Map<String, String> map : myMapList ){
    System.out.println(map.get("Id"));
    System.out.println(map.get("Name"));
    System.out.println(map.get("Description"));
    System.out.println(map.get("LocationCountryId"));
 }

Upvotes: 0

Robby Cornelissen
Robby Cornelissen

Reputation: 97227

You could implement your own ResultTransformer similar to the one specified by Criteria.ALIAS_TO_ENTITY_MAP. Instead of using a HashMap, you'll need to use a LinkedHashMap to preserve the insertion order of the elements.

It could look something like this:

import java.util.LinkedHashMap;
import java.util.Map;

public class AliasToLinkedEntityMapTransformer extends
        AliasedTupleSubsetResultTransformer {

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

    @Override
    public boolean isTransformedValueATupleElement(String[] aliases,
            int tupleLength) {

        return false;
    }
}

Upvotes: 1

Related Questions