Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a list of specific type instead of List<Object[]> in Hibernate?

I have tree of classes:

classA {  
      classB b;  
      classC c;
      .....
} 

I have HQL query like this:

SELECT a.field1, b.field2, c.field3, c.field4
FROM a LEFT OUTER JOIN b ON a.id = b.fk
       LEFT OUTER JOIN c ON b.id = c.fk 

This query returns List<Object[]>.

Is it possible to cast the returned data to the following class:

classD {
    Type1 fiedl1;
    Type2 field2;
    Type3 field3;
}

So can casting be made by Hibernate or I need manually do all casting?

like image 244
user810430 Avatar asked May 31 '12 07:05

user810430


2 Answers

There are different types of selects in JPA queries. You are currently using Array as a return type, what you need is Construct return type. Here is how to achieve this:

String queryStr =
    "select NEW package.YourDefinedCustomClass(
     a.field1, b.field2, c.field3, c.field4) from a left outer join b 
     on a.id=b.fk left outer join c on b.id=c.fk";

TypedQuery<YourDefinedCustomClass> query =
    em.createQuery(queryStr, YourDefinedCustomClass.class);

List<YourDefinedCustomClass> results = query.getResultList();

Basically there are two things:

  1. Custom class must be your results return type
  2. Custom class must have a constructor which takes result values you define in query string.

Read more on selects in JPA2 queries.

like image 63
JMelnik Avatar answered Sep 28 '22 21:09

JMelnik


If you are really sure you can do type casts.

 List<classD> newlist = ...;
 for(Object o : list){
      newlist.add((classD) o);
 }

Be careful with this though

So yes. Manual casting. (note: with arrays (you can directly cast) )

like image 44
tgoossens Avatar answered Sep 28 '22 23:09

tgoossens