HQL collection in select clause?

Is it possible to select a collection in HQL?

Classes

Class Author
----------------
String name
List<Books>

Class Book
---------------
String name
String category
Author author

HQL

select author.name, elements(book.name)
from Author author
inner join author.books book
where book.category = "fiction"

and the query.list() function would return a list of: String, List<String> ?

contributors is a Collection. As such, it does not have an attribute named id.

Id is an attribute of the elements of this Collection. shareit app

You can fix the issue by joining the collection instead of dereferencing it:

SELECT p 
  FROM Project pj 
  JOIN pj.contributors  p 
 WHERE pj.id       = :pId
   AND p.Id     = :cId

So then I would essentially need to group the rows of contributors into a Project myself? The problem is my real query I am using (not the example I posted) is more complex and grabs from two sub collections, kind of like this:

SELECT pj.name, c.name, m.name 
  FROM Project pj 
  JOIN pj.contributors  c 
  JOIN pj.maintainers   m

This produces tons of rows since cartesian product. I could do 2 separate queries and try to join them, but this requires a lot of work outside the query, which is why I was looking for something more like what I first posted if hibernate can somehow transform them into lists for me.

I’ve been doing a lot of reading this week trying to figure this out, and I think this essentially gives me an answer here:

If you need to fetch multiple child associations, it's better to fetch one collection in the initial query and the second one with a secondary SQL query.

I guess that is just kind of common sense, I was hoping Hibernate could somehow do this for you behind the scenes.

You have more or less two options in HQL. Either you fetch an entity along with associations or you list all attributes individually that you want to fetch in the select list and work with Object[] or Tuple.

You could use the following HQL:

select author
from Author author
join fetch author.books book
where exists (
  select 1
  from author.books b
  where b.category = "fiction"
)

This will return a List<Author> with all books fetched that wrote at least one book in the category “fiction”.