如何将jpa(hibernate)查询结果列表作为HashMap?

时间:2012-02-15 10:07:33

标签: java hibernate jpa hashmap

目前,我的任务是为客户端解析器准备文档服务,用户可以查看,编辑和管理允许的文档。 Documentprivileges对文档模型有@onetomany关系。我已按文档

添加了获取单一权限
  public String getDocumentPrivilege(Long documentId);
    ......

我还想通过overriden方法返回HashMap(docId和privilege)。到目前为止,我已经完成了:

@Override
    public HashMap<Long, String> getDocumentPrivilege(List<Long> documentIds)
    {
        Query q = null;
        if (documentIds != null && documentIds.size()>0) {
            q = em.createQuery("select new map(d.document_id as id, d.privilege as privilege) from DocumentPrivileges d"
                    + " where d.document_id IN ?1");
            q.setParameter(1, documentIds);
            @SuppressWarnings("unchecked")
            HashMap<Long, String> results = (HashMap<Long, String>) q.getResultList();
            if(results != null && results.size()>0)
            return results;
        }
        return null;
    }

但我收到以下错误:

Caused by: org.hibernate.hql.ast.QuerySyntaxException: unexpected token: : near line 1, column 140 [select new map(d.document_id as id, d.privilege as privilege) from xxx.xxxx.xxxx.xxxmodel.DocumentPrivileges d where d.document_id IN :docs]
    at org.hibernate.hql.ast.QuerySyntaxException.convert(QuerySyntaxException.java:54)
    at org.hibernate.hql.ast.QuerySyntaxException.convert(QuerySyntaxException.java:47)
    at org.hibernate.hql.ast.ErrorCounter.throwQueryException(ErrorCounter.java:82)
    at org.hibernate.hql.ast.QueryTranslatorImpl.parse(QueryTranslatorImpl.java:284)
    at org.hibernate.hql.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:182)
    at org.hibernate.hql.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:136)
    at org.hibernate.engine.query.HQLQueryPlan.<init>(HQLQueryPlan.java:101)
    at org.hibernate.engine.query.HQLQueryPlan.<init>(HQLQueryPlan.java:80)
    at org.hibernate.engine.query.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:98)
    at org.hibernate.impl.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:156)
    at org.hibernate.impl.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:135)
    at org.hibernate.impl.SessionImpl.createQuery(SessionImpl.java:1760)
    at org.hibernate.ejb.AbstractEntityManagerImpl.createQuery(AbstractEntityManagerImpl.java:268)
    ... 136 more

我检查了其他相似的例子。我是否采取了错误的方式?

2 个答案:

答案 0 :(得分:0)

地图预定义为map<column, value>而不是map<column1value, column2value>您必须从结果列表中构建地图

答案 1 :(得分:0)

您必须使用setParameterList,在查询中将documentId列表设置为与HQL的运算符“IN”一起使用。