How to return Map<Key, Value> with Hibernate\HQL

旧城冷巷雨未停 提交于 2020-01-05 03:18:29

问题


I have an entry as follow:

@Entity
@Table(name="rank")
class Rank implements Serializable {
 private int id;
 private int rank_id;
 private date creationDate;
 ...
 // getters\setters...
}

I would like to query this table and put the results into a HashMap! as follow:

Map<Integer, Rank> = session.createSQL("select new map...").list();

Is this possible to put the entity as the value of the map?

Can I get a code example?


回答1:


Yes, for example:

Select new Map(r.id,r) FROM Rank r

But that will return a list of Maps. You should take a look here to understand better.

Edit: To explain better, the return will be something like this:

List<Map<Long, Rank>> ranks = (List<Map<Long, Rank>>) session.createQuery("select new Map<r.rankId,r> FROM Rank r").list();

It is one Map for each record. To put all in only one map, unfortunately, it has to be manually:

List<Rank> ranks = (List<Rank>) session.createQuery("select new r FROM Rank r").list();
Map<Long, Rank> mapRanks  = new HashMap<Long, Rank>();
for (Rank rank : ranks) {
  if (!map.contains(rank.getId()) {
    map.put(rank.getId(), rank);
  }
}


来源:https://stackoverflow.com/questions/31521080/how-to-return-mapkey-value-with-hibernate-hql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!