Home  >  Article  >  Java  >  ## Why Does Hibernate Criteria Return Duplicate Orders with FetchType.EAGER?

## Why Does Hibernate Criteria Return Duplicate Orders with FetchType.EAGER?

Linda Hamilton
Linda HamiltonOriginal
2024-10-26 04:18:02428browse

## 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn