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