radai
radai

Reputation: 24192

hql - how to populate a child entity's lazy collection when fetching the parent

suppose i have @Entity A, which has an eager @ManyToOne to @Entity B, and this B has a lazy (default) @OneToMany to a collection called "images"

i want to do something like:

"select a from A a join fetch a.b.images where a.b = :b"

this is a query that finds an instance of A given an instance of B (the A-->B link is unidirectional from A). trying something like the above approach lands me a hibernate exception:

query specified join fetching, but the owner of the fetched association was not present in the select list

but trying something like

"select a, a.b.images from ..."

will return multiple results for every instance of A (multiplied by the amount of images)

how do i write a query on A that populates a.b.images ?

Upvotes: 0

Views: 1460

Answers (1)

gkamal
gkamal

Reputation: 21000

Try this - you first need to join fetch a.b assign an alias and then join fetch alias.images. Check docs for more details. It would not be a good idea to do this if a.b and b.images are both one-to-many - it will lead to a result set explosion. Something like batch-size or sub-select would be a better way to optimize it.

"select a from A a join fetch a.b x join fetch x.images where a.b = :b"

Upvotes: 1

Related Questions