Hibernate SQLQuery list method returns Object instead of object array
Andrew Mclaughlin
I have this strange behavior with Hibernate SQLQuery.list() method.
Following is the description of the issue:
I have a sql select query which retrieves only single column(group) from the database (i.e., select group from peopleGroup where groupid = 10)
And i'm recieving the result of the above list in List of Object array
i.e,
SQLQuery hQuery = session.createSQLQuery("select group from peopleGroup where groupid = 10");
List<Object[]> result = (List<Object[]>)hQuery.list();Ideally, the result should contain a list of object arrays but when I inspect, 0'th index of the result contains String object instead of an Object array.
However if I use more than one column let's say 2 columns in the select clause of the query I was able to see that 0'th index of the result as Object array i.e., Object[2]={"group","groupid"};
How do I get the Object array even if I have only one column mentioned in the select clause of the query?
13 Answers
Docs states:
List list()
Return the query results as a List. If the query contains multiple results per row, the results are returned in an instance of Object[].
Convert it by yourself, like so.
List<Object[]> l = new ArrayList<>();
for(Object o : query.list()) { Object[] arr = {o}; l.add(arr);
} 2 you can create a object mapper like below code
public class QueryMapper { private String group; //setter and getter }And you have to change your code like below
SQLQuery hQuery = session.createSQLQuery("select group from peopleGroup where groupid = 10");
List<Object[]> result = (List<Object[]>)hQuery.list();
List<QueryMapper> list = new ArrayList<QueryMapper>(); for(Object[] object: result){ QueryMapper queryMapper = new QueryMapper(); if(object[0]!=null){ queryMapper.setGroup((String)object[2]); } list.add(queryMapper); } All i wanted is to fix the ClassCastException which was caught during the assignment of result.get(0) to the container i.e., container = result.get(0);
Since the value returned by mentioned list() method contains object in case of single column in the select clause of the query and i won't be allowed to cast from certain object to Object[](Object array). Instead i have tried a work around like below
Already existing code
SQLQuery hQuery = session.createSQLQuery("select group from peopleGroup where groupid = 10");
List<Object[]> result = (List<Object[]>)hQuery.list();
Object[] container = result.get(0);now i have put condition like below to decide how to assign value to the Object[]
SQLQuery hQuery = session.createSQLQuery("select group from peopleGroup where groupid = 10");
List<Object[]> result = (List<Object[]>)hQuery.list();
Object[] container = null;
if(result.get(0) instanceof Object[]) container = result.get(0);
else { container = new Object[1]; container[0] = result.get(0); }The above solution seems working in my case !