1

Currently i am getting List of Object form Hibernate Query

My code is:

session.createSQLQuery("SELECT c.EMP_ID, COUNT(*) FROM employee c WHERE c.CITY=:someCity")
List<Object[]> objList =myQuery.list();

Here i am getting only two parameters EMP_ID and COUNT

Is there any way so i can Map like

Map<int empId, int count> objList =myQuery.someMethod();
Neil Stockton
  • 11,383
  • 3
  • 34
  • 29
iTech
  • 13
  • 1
  • 8
  • 4
    possible duplicate http://stackoverflow.com/questions/7876724/how-to-return-mapkey-value-with-hql, http://stackoverflow.com/questions/925363/how-to-fetch-hibernate-query-result-as-associative-array-of-list-or-hashmap – geco17 Feb 13 '16 at 10:03

2 Answers2

2

You can change your Query as follows:

"SELECT new map(c.EMP_ID as empId, COUNT(*) as empCount) FROM employee c WHERE c.CITY=:someCity"

Now this will return you the List of the Map with Keys empId & empCount.

Here is a quick code snippet:

List<?> objList = session.createQuery("SELECT new map(c.EMP_ID as empId, 
                  COUNT(*) as empCount) FROM employee c WHERE c.CITY=:someCity").list();
Iterator<?> myRows = objList.iterator();    
while (myRows.hasNext()) {
    Map row = (Map) myRows.next();
    System.out.println(row);
}

Output:

{empId=1, empCount=10}
{empId=2, empCount=20}
{empId=3, empCount=30}
user2004685
  • 9,548
  • 5
  • 37
  • 54
2

As you are using createSQLQuery, it will give you a result set of two length arrays. You have to build the map manually, like below

for(Object[] row : objList ) {
    map.put(row[0], row[1]);
}
M Sach
  • 33,416
  • 76
  • 221
  • 314