如何从JPA查询返回HashMap? [英] How to return HashMap from JPA query?

查看:193
本文介绍了如何从JPA查询返回HashMap?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从JPA查询中返回一个HashMap,如下所示,但我不知道如何从该查询中填充HashMap.实际上,我想从前端的HashMap填充图表

I want to return a HashMap from JPA query like the below but I don't know how to fill the HashMap from this query. Actually I want to fill charts from HashMap in the frontend

public HashMap<String,String> getCount(Date start,Date end) {
           HashMap<String, String> map=new HashMap<String, String>();
            Query q = 
                  em.createQuery(
                    "select count(i.uuid),i.username from Information i where i.entereddt between :start and :end group by i.username");
                q.setParameter("start",new Timestamp(start.getTime()));
                q.setParameter("end",new Timestamp(end.getTime()));

                 System.out.println(" query"+ q.getResultList().get(0).toString());

             return map;
        }

有什么建议吗?

推荐答案

您似乎正在尝试执行一个查询,该查询返回的类型未映射到您拥有的任何Java实体(如果存在,则您从未提及它们).在这种情况下,您要使用createNativeQuery(),它将返回类型为Object[]List.

It appears that you were trying to execute a query which return types not mapped to any Java entities you have (or if they be present you never mentioned them). In this case, you want to use createNativeQuery(), which will return a List of type Object[].

尝试使用此版本的方法:

Try using this version of the method:

public HashMap<String,String> getCount(Date start,Date end) {
    HashMap<String, String> map=new HashMap<String, String>();
    Query q = em.createNativeQuery(
                    "select count(i.uuid),i.username from Information i" +
                    "where i.entereddt between :start and :end group by i.username");
    q.setParameter("start",new Timestamp(start.getTime()));
    q.setParameter("end",new Timestamp(end.getTime()));

    List<Object[]> list = query.getResultList();

    for (Object[] result : list) {
        map.put(result[0].toString(), result[1].toString());
    }

    return map;
}

这篇关于如何从JPA查询返回HashMap?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆