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; }
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(); }
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);
Additional Resources
For further insights on this behavior, refer to the following resources:
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!