Home >Java >javaTutorial >## Why Does Hibernate Criteria Return Duplicate Orders with FetchType.EAGER?
Hibernate Criteria Returns Duplicate Orders with FetchType.EAGER
Question:
When setting the fetch type of an order's orderTransactions list to FetchType.EAGER, why do the orders appear multiple times in the resulting list retrieved using Criteria?
Answer:
This behavior is expected. With FetchType.EAGER, a join is performed to eagerly fetch the orderTransactions. This results in the same number of results as a standard SQL join, where each order will be present in the result set for each corresponding orderTransaction.
To understand this, consider the SQL statement generated:
SELECT o.*, l.* from ORDER o LEFT OUTER JOIN LINE_ITEMS l ON o.ID = l.ORDER_ID
In this statement, for every order, all the related line items will be retrieved, leading to multiple instances of the same order in the result set.
Solution to Obtain Distinct Results:
To filter out duplicate results with FetchType.EAGER, you can use a Collection type that maintains insertion order, such as a LinkedHashSet:
Collection<Order> result = new LinkedHashSet( session.createCriteria(Order.class) .add(Restrictions.in("orderStatus", orderFilter.getStatusesToShow())) .list() );
The above is the detailed content of ## Why Does Hibernate Criteria Return Duplicate Orders with FetchType.EAGER?. For more information, please follow other related articles on the PHP Chinese website!