将Hibernate查询结果存储到Hashmap

时间:2016-06-30 19:08:41

标签: java hibernate collections hashmap

我想将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());

1 个答案:

答案 0 :(得分:3)

您可以将其全部放在一个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());
}