Search code examples
hibernatejpa

Hibernate JPA Native Query ResultSet


I need to get a resultset via executing a native query in Hibernate. Though I am using EntityManager, the query and resultSet may not be entities.

A need to get ResultSet that is of List. Since the select output may vary (read dynamic) i cannot use SqlResultSetMapping.

When i tried the below code i got a result. Since what i am requesting is a single valued result. (Hibernate JPA)

Query query = manager.createNativeQuery("select name from fresher_test where id=1");
List<Object> amount = query.getResultList();

if(amount == null)
 {
    System.out.println("Hey its a null");
    return;
 }
 for(Object e : arr)
 {
   System.out.println(e.toString());
 }

The output was : Alice

When I tried to get more than one select out from the same code with Query as select name,designation from fresher_test where id=1

The output was : [Ljava.lang.Object;@8b1a4f

An object. How do I get the fields from this object?. I tried to typecast object e (List l = (List) e;) to a List but i throws java.lang.ClassCastException: java.lang.String cannot be cast to java.util.List.

This there a way that I could get the values in a List or Array ??

Note : I cannot use a result class/entity since the results could be dynamic.


Solution

  • When fetching multiple columns, the result is a List<Object[]>. Each Object[] contains one column of the row. So in your case, each Object[] would contain 2 elements, the first one being the name, and the second one being the designation.

    Note that getResultList() will never return null. You shouldn't check that.