8

I have a structure like this:

  • A contains collection of B (mapped as not-lazy)
  • B contains collection of C (mapped as not-lazy)

I'd like to make a query, that retrieves A objects, that contain B objects without the C objects within them. Is that possible? The other way around will work for me too (if B-C relation is mapped lazy and the query retrieves A, containing B and C).

Thanks!

1

1 Answer 1

9

No, it's not possible. Since you marked the association itself as eagerly-loaded, Hibernate will always load this association eagerly.

If you mark the association as lazy (the default for toMany associations), then you have th option of eagerly fetching them in a query, using a join fetch:

select a from A a left join fetch a.bs b left join fetch b.cs

Note that this will not work if both of the collections are bags (i.e. Lists without index column).

Sign up to request clarification or add additional context in comments.

4 Comments

Hello, thanks for the answer. I found this topic too, the answer is the same: stackoverflow.com/questions/3516873/… But I'm having some troubles making it work fine- it multiplies the "A" many times. Most likely my mistake.
Solved it, "distinct" is needed to make it work properly (I'm not an expert and I have no idea what's the difference). I'll mark this as correct answer, but it will be nice if you edit it or tell me where the difference is :)
Without distinct, Hibernate returns 1 result per row of the JDBC resultset. This means that if you just have one A with 2 Bs, and each B has 2 Cs, the query will return 4 rows, and the list will contain 4 times the same instance of A. The distinct keyword makes Hibernate remove duplicates from the list.
Thanks you very much, after a day of banging my head in the wall, I've solved my issues ^^

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.