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

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

Barbara Streisand
Release: 2024-10-26 01:40:28
Original
760 people have browsed it

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

Hibernate Criteria Returns Duplicate Orders with FetchType.EAGER

Consider the following Hibernate mapping:

@OneToMany(targetEntity = OrderTransaction.class, cascade = CascadeType.ALL)
public List<OrderTransaction> getOrderTransactions() {
    return orderTransactions;
}
Copy after login

With this mapping, you can filter orders using their orderStatus field:

public List<Order> getOrderForProduct(OrderFilter orderFilter) {
    Criteria criteria = getHibernateSession()
            .createCriteria(Order.class)
            .add(Restrictions.in("orderStatus", orderFilter.getStatusesToShow()));
    return criteria.list();
}
Copy after login

However, when the fetch type is explicitly set to EAGER, the resulting list contains duplicate orders.

The Reason for Duplicates

With FetchType.EAGER, Hibernate performs a join operation to eagerly fetch the associated OrderTransactions. As a result, each Order in the resulting list will be duplicated for every associated OrderTransaction. This is the expected behavior in this scenario.

Achieving Distinct Results

To obtain distinct orders despite the eager fetching, you can utilize the following code in your Criteria query:

Criteria criteria = getHibernateSession()
            .createCriteria(Order.class, "o")
            .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
Copy after login

Additional Resources

For further insights on this behavior, refer to the following resources:

  • [Hibernate FAQ on Distinct Results for Outer Join Fetching](https://docs.jboss.org/hibernate/orm/5.3/javadocs/faq/FAQ.html#ch02s01)
  • [Gavin King's Explanation of SQL Outer Joins and Hibernate Behavior](http://www.hibernate.org/42.html)

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template