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
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 usingquery.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().When you select a single entity,
query.list()
will return aList
ofObject
containing your entities.When you select multiple entities,
query.list()
will return aList
ofObject[]
. 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
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:
Or a list:
http://docs.jboss.org/hibernate/core/3.3/reference/en/html/queryhql.html#queryhql-select