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!

Ask613
  • 2,775
  • 1
  • 19
  • 27
Mooncrosser
  • 139
  • 1
  • 2
  • 9
  • Possible duplicate of [Hibernate: Overriding mapping's EAGER in HQL?](http://stackoverflow.com/questions/3072568/hibernate-overriding-mappings-eager-in-hql) – davidwebster48 Oct 21 '15 at 01:59

1 Answers1

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).

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • Hello, thanks for the answer. I found this topic too, the answer is the same: http://stackoverflow.com/questions/3516873/hql-fetch-join-collections-from-eager-table But I'm having some troubles making it work fine- it multiplies the "A" many times. Most likely my mistake. – Mooncrosser May 14 '12 at 13:44
  • 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 :) – Mooncrosser May 14 '12 at 13:57
  • 1
    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. – JB Nizet May 14 '12 at 14:16
  • Thanks you very much, after a day of banging my head in the wall, I've solved my issues ^^ – Mooncrosser May 14 '12 at 14:58