28

If my query contains one class, like:

query = session.createQuery("select u from User as u");
queryResult = query.list();

then I iterate it, where queryResult is an object of User class.

So how to get result from query which contains more than one class? For example:

select u, g from User as u, Group as g where u.groupId = g.groupId and g.groupId = 1
Tom11
  • 2,199
  • 6
  • 26
  • 50
yaya
  • 291
  • 1
  • 3
  • 7
  • 1
    Best answer is here http://stackoverflow.com/questions/5435304/how-to-override-hibernate-fetching-strategy-at-runtime – Arjun Mishra Apr 22 '17 at 01:22

4 Answers4

32
for (Object[] result : query.list()) {
    User user = (User) result[0];
    Group group = (Group) result[1];
}
Nicolas Henneaux
  • 9,769
  • 10
  • 44
  • 71
PonomarevMM
  • 442
  • 3
  • 4
7

You can do that using Tuples I believe, but more importantly, if your Group and User is related like that query seems to suggest User should have a Group field (don't use groupId in your User class, hibernate should sort this out for you). If that's the case you can simply query it using select u from User u join fetch u.group g where g.groupId = :id (then set the id using query.setParameter(1, id);.

The fetch keyword in that query makes it an eager load so both objects will be returned to hibernate which will return the User object to you. Access the Group object using user.getGroup().

Thor84no
  • 5,318
  • 1
  • 27
  • 53
  • I think that this is right way, but i had some parser errors: expecting "all", found 'join' and expecting "by", found 'where' – yaya Oct 27 '11 at 09:16
  • It's `join fetch` rather than `fetch join`, my mistake. Correcting it now. – Thor84no Oct 27 '11 at 09:31
4

When you select a single entity, query.list() will return a List of Object containing your entities.

When you select multiple entities, query.list() will return a List of Object[]. Each element of the array reresents a separate entity.

Read more here: http://docs.jboss.org/hibernate/core/3.3/reference/en/html/queryhql.html#queryhql-select

Marc
  • 3,016
  • 2
  • 24
  • 36
Luka Klepec
  • 503
  • 3
  • 12
0

Also you can create a constructor and return a object:

Assuming that the class Family has an appropriate constructor - as an actual typesafe Java object:

select new Family(mother, mate, offspr)
from DomesticCat as mother
join mother.mate as mate
left join mother.kittens as offspr

Or a list:

select new list(mother, offspr, mate.name)
from DomesticCat as mother
inner join mother.mate as mate
left outer join mother.kittens as offspr

http://docs.jboss.org/hibernate/core/3.3/reference/en/html/queryhql.html#queryhql-select

Jason Glez
  • 624
  • 1
  • 10
  • 14