Learner
Learner

Reputation: 21405

What are the duplicates that are returned by Hibernate queries for collections

The hibernate documentation for executing queries says that:

Queries that make use of eager fetching of collections usually return duplicates of the root objects, but with their collections initialized. You can filter these duplicates through a Set.

For example if I have an Order class with list of OrderLines having one-to-many mapping between them. Then if I use Hibernate queries, in this context is my Order class called as root object? Then why Hibernate wants to load duplicate elements at all?

Please help me in understanding this, I am new to Hibernate so finding it difficult to understand the concept.

Upvotes: 3

Views: 254

Answers (1)

JB Nizet
JB Nizet

Reputation: 691765

The root entity is the entity which is selected by the query:

select o from Order o ...

In this case, o is the root, of type Order.

Now if you do

select o from Order o left join fetch o.lines

and you have 2 orders, each with 3 lines, in database, then the underlying SQL query will return 6 rows, and Hibernate will also return a list of 6 Order objects. But the list will contain the first order 3 times, and the second order 3 times.

You can avoid this by

  • using Set<Order> deduplicated = new HashSet<Order>(listOfOrders)
  • adding the distinct keyword to the query:

    select distinct o from Order o left join fetch o.lines
    

Upvotes: 4

Related Questions