1

I have class A which have collection of B's: List<B> bList. Also, B class have collection of C: List<C> cList

Question: How I can get object with all collections initialized?

This NamedQuery works incorrectly (it returns many duplicates of B):

SELECT a FROM A a 
LEFT JOIN FETCH a.bList bList 
LEFT JOIN FETCH bList.cList 
WHERE a.id = (:id)
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
WelcomeTo
  • 19,843
  • 53
  • 170
  • 286
  • Your query is fine. Duplicates are expected with Fetch join. You need to deal with these. See here: http://stackoverflow.com/questions/1995080/hibernate-criteria-returns-children-multiple-times-with-fetchtype-eager – Alan Hay Nov 21 '13 at 10:31

1 Answers1

-1

Use SELECT DISTINCT a instead of SELECT a. It will remove all duplicate entries in the result. Your query would be:

SELECT DISTINCT a FROM A a 
LEFT JOIN FETCH a.bList bList 
LEFT JOIN FETCH bList.cList 
WHERE a.id = (:id)
thanhnguyen
  • 214
  • 2
  • 5
  • I'm not sure that will work. https://community.jboss.org/wiki/HibernateFAQ-AdvancedProblems#jive_content_id_Hibernate_does_not_return_distinct_results_for_a_query_with_outer_join_fetching_enabled_for_a_collection_even_if_I_use_the_distinct_keyword – Alan Hay Nov 21 '13 at 16:25
  • @Alan Hay: When we use DISTINCT keyword in HQL, it does not force the database to filter distinct objects. Instead, this filtering of duplicates happens in-memory, when the resultset is marshalled into objects. Of course, this mechanism slows down the process since it need to process duplicate entries in memory, but at least from the user perspective, the returned result is what we expect. – thanhnguyen Nov 21 '13 at 17:10
  • Sorry, but it don't work. It still returns duplicates. (I apologize above query will remove duplicates only of A instance, but I have duplicates in `bList`. Thanks – WelcomeTo Nov 21 '13 at 17:18
  • @user3005451. Fair enough however it is not going to fix the problem. – Alan Hay Nov 21 '13 at 17:37
  • You can change from `List` to `Set` in collections of _B_ and _C_ to remove duplication if it does not change the semantic of your application. – thanhnguyen Nov 22 '13 at 07:05