• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

left join fetch returns duplicates

 
Slava Lovkiy
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have Cat and Kitten entities, that are in many-to-one relationship (Cat has many kittens)
I need to return those Cats and only those Kittens of that Cat that matches certain conditions.

I.e.

from Cat cat
left join fetch cat.kittens kitten
where kitten.color = 'gray'


Using this hql i ran into the following problem:
If one Cat has N 'gray' kittens, I got N instances of the same Cat returned with N kittens pre-loaded in Cat.kittens collection.

If I will use 'left join' w/o 'fetch' I got correct number of Cats, but Cat.kittens now contains all kittens, including 'gray'.

The 'distinct' keyword doesnt work for me too.

Any idea how to avoid duplication in result list?
 
Christian Bauer
author
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Set resultSet = new HashSet( q.list() );
 
Slava Lovkiy
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It won't work correctly in case of pagination of results. Number of rows will be calculated before removing dups.
 
Christian Bauer
author
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can't use pagination with an outer join fetch. If you start thinking about the SQL and how the resultset looks like, it should be quite obvious why it doesn't work.
 
Slava Lovkiy
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Indeed.

Looks like I will need to refactor query to not fetch 'one-to-many' assosiations in one select. However, is there any other ways to make Hibernate lazy loading of assosiated objects using some criteria restrictions ?
I found session.filter(collection, "hql") not suitable since it returns the subset of elemnts in list rather then list as property of selected object.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic