【问题标题】:Store Hibernate query results into Hashmap将 Hibernate 查询结果存储到 Hashmap
【发布时间】:2016-06-30 19:08:40
【问题描述】:

我想将 HQL 查询结果的名称和 id 存储到 Hashmap 中。这是我的代码。有没有更好的办法?

    String hql = "FROM Student";
    Session session = HibernateUtil.getSessionFactory().openSession();
    Query query = session.createQuery(hql);
    List queryResults = query.list();
    List<Student> result = new ArrayList<Student>();

    Iterator it = queryResults.iterator();
    while (it.hasNext()) {
        Student student = (Student) it.next();
        result.add(student);
    }
    Map mapresult = new LinkedHashMap<Integer,String>();

    for (Student Maprslt : result)
        mapresult.put(Maprslt.getId(), Maprslt.getName());

【问题讨论】:

    标签: java hibernate collections hashmap


    【解决方案1】:

    您可以将所有内容放在一个 foreach 循环中,该循环旨在循环 Iterable 或数组。

    String hql = "FROM Student";
    Session session = HibernateUtil.getSessionFactory().openSession();
    Query query = session.createQuery(hql);
    List queryResults = query.list();
    
    Map<Integer,String> mapresult = new LinkedHashMap<>();
    for (Object obj : queryResults) {
        Student student = (Student) obj;
        mapresult.put(student.getId(), student.getName());
    }
    

    【讨论】:

      猜你喜欢
      • 2019-12-29
      • 2012-11-05
      • 2021-11-09
      • 1970-01-01
      • 1970-01-01
      • 2014-02-11
      • 2012-06-12
      • 2022-01-25
      • 1970-01-01
      相关资源
      最近更新 更多