2

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?

Shvalb
  • 1,835
  • 2
  • 30
  • 60
  • dont think so but work around would be execute sql get the list, traverse and create map out it. – Subhrajyoti Majumder Jul 20 '15 at 15:59
  • Duplicate http://stackoverflow.com/questions/7876724/how-to-return-mapkey-value-with-hql – 6ton Jul 20 '15 at 16:02
  • It's not a duplicate - I'm interested to know how the syntax works for creating the result HashMap when the value of the map is an Hibernate entity (row in the table). if it's possible at all... – Shvalb Jul 20 '15 at 16:12

1 Answers1

6

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);
  }
}
Community
  • 1
  • 1
Sertage
  • 3,123
  • 1
  • 19
  • 26