newuserhibernate
newuserhibernate

Reputation: 3

Hibernate native query return List Object List

I am using an hibernate NQL query which fetches me two columns :

SELECT object_name, 
       object_name_location 
FROM   dbo.object_stacks 
WHERE  object_id IN (SELECT thumb_nail_obj_id 
                     FROM   dbo.uois 
                     WHERE  Upper(NAME) LIKE Upper('%testobj%')) 

When I select only one column i.e only object name - everything works fine but with two columns I am getting an error

java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to java.lang.String

at run time when I try to display result from the list. I tried using String array in the list as well but it doesn't work. Below are my code snippets which give error :

When I use only List :

List<String> Thumbnailpaths = pathquery.list();
System.out.println(Thumbnailpaths.get(i).replace("\\", "\\\\"));

No error at compile time also nothing if leave it as it is but above line to display gives classcast exception.

When I use List array :

List<String[]> Thumbnailpaths = pathquery.list();

System.out.println(Thumbnailpaths.get(i)[0].replace("\\", "\\\\"));

Here again classcast exception at runtime

Also Criteria.ALIAS_TO_ENTITY_MAP doesn't help at all as it makes logic much more complex. I just need 2 column values from a database table.

Please let me know if there is any solution to fetch multiple column results in NQL and then put in list.

Note : Looks like here generics are not displaying and only List is being written in my code snippet

Upvotes: 0

Views: 16721

Answers (2)

Abhijeet
Abhijeet

Reputation: 4309

Unfortunately, Hibernate doesn't provide a standard way to retrieve the results for columns of table and store directly to Entity Object.You have to manually parse the data fetched by your query.

The hibernate query will return List of Object Array i.e. List<Object[]>. Object[] will contain data from your columns. List is nothing but rows retrieved by query. In your case you can refer following code :

List<Object[]> Thumbnailpaths = pathquery.list();
for(Object[] objArr : Thumbnailpaths)
{
    String objName = (String)objArr[0];
    String objNameLocation = (String)objArr[1];
    System.out.println(objName + " : " +objNameLocation);
}

Above code will help you parse the object[]

Upvotes: 2

Liping Huang
Liping Huang

Reputation: 4476

Yes, hibernate will return the Object arrays (Object[]) for this case - return multiple columns. but you still can using the "Entity queries" to return a entity objects rather then the "raw" value.

Upvotes: 0

Related Questions