如何从JPA查询返回HashMap?

时间:2015-08-05 05:00:30

标签: jpa

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

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

有什么建议吗?

3 个答案:

答案 0 :(得分:9)

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

尝试使用此版本的方法:

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

答案 1 :(得分:2)

请参阅JPA 2.0 native query results as map

Postgres的案例中,它就像是,

List<String> list = em.createNativeQuery("select cast(json_object_agg(count(i.uuid),i.username) as text) from schema.information i where i.entereddt between :start and :end group by i.username")
                   .setParameter("start",new Timestamp(start.getTime()))
                   .setParameter("end",new Timestamp(end.getTime()))
                   .getResultList();

//handle exception here, this is just sample
Map map = new ObjectMapper().readValue(list.get(0), Map.class);

请注意,我只是与Postgres分享我的解决方法。

答案 2 :(得分:0)

我知道这是一个老问题,但是您可以创建一个对象来存储信息

public class UserCount {
   private String username;
   private Long count;

   public UserCount(String user, Long count){
      this.username = user;
      this.count = count;
   }

}

创建构造函数并以正确的方式传递参数很重要。

JPQL成为

select my.package.UserCount(i.username, count(i.uuid) ) from schema.information i where i.entereddt between :start and :end group by i.username

查询返回List<UserCount>