【问题标题】:HQL query returns a map which does not have the same order as specified in the queryHQL 查询返回的地图与查询中指定的顺序不同
【发布时间】:2015-07-24 09:52:42
【问题描述】:

我正在执行这样的 HQL 查询:(hql 查询将是动态的,具有不同的列名、列数、数据类型)

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());
}

输出:

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

在地图中,我想获得与我在查询中选择的顺序相同的顺序。 在查询中,我选择了idnamedescriptionlocationCountryId,但在地图中我以不同的顺序获取条目。

那么如何得到与查询中指定的相同的顺序呢?

【问题讨论】:

  • 什么版本的 Hibernate?

标签: java hibernate hql


【解决方案1】:

您可以实现自己的ResultTransformer,类似于Criteria.ALIAS_TO_ENTITY_MAP 指定的那个。您需要使用LinkedHashMap 来保留元素的插入顺序,而不是使用HashMap

它可能看起来像这样:

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;
    }
}

【讨论】:

  • 我试图用你的代码创建一个类.. AliasedTupleSubsetResultTransformer 。该课程不可用。让我进一步了解。对不起,如果我错了
  • 您使用的是什么版本的 Hibernate?你的类路径中有hibernate-core 吗?我的解决方案是基于Hibernate 4.3.8,果然,类应该在那里:docs.jboss.org/hibernate/orm/4.3/javadocs/org/hibernate/…
  • 我正在使用 Maven。 org.hibernatehibernate-core3.3.2.GA。 hibernate 核心在我的 eclipse 构建路径中。
【解决方案2】:

地图不保证顺序。

参考:Link

请允许我修改您的代码,

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"));
 }

【讨论】:

  • 对不起,我的问题中没有提到这一点。这里的查询是动态的,所以我不能使用 map.get(key)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多