Home  >  Article  >  Java  >  Why Does Hibernate Criteria Return Multiple Copies of Children When Using FetchType.EAGER?

Why Does Hibernate Criteria Return Multiple Copies of Children When Using FetchType.EAGER?

DDD
DDDOriginal
2024-10-27 04:29:29412browse

Why Does Hibernate Criteria Return Multiple Copies of Children When Using FetchType.EAGER?

Hibernate Criteria Returns Multiple Copies of Children with FetchType.EAGER

When mapping a one-to-many relationship in Hibernate, such as the Order class having a list of OrderTransactions, it is common to use the FetchType.EAGER setting to eagerly fetch the child entities during the initialization of the parent. However, a curious phenomenon arises when using this setting with Hibernate Criteria.

Query Results Repeat Orders

Consider the following scenario: An Order class is defined with a list of OrderTransactions, and a Criteria query is used to filter orders based on their orderStatus. With the default FetchType.LAZY setting, the result list contains unique Order instances as expected. But upon setting FetchType.EAGER for the OrderTransaction mapping, the Order instances start appearing multiple times in the results.

Expected Behavior with FetchType.EAGER

Although the behavior of repeated Orders with FetchType.EAGER may seem unexpected, it aligns with the underlying SQL behavior. When an outer join is performed (which occurs due to FetchType.EAGER), the resultset contains all potential combinations of parent and child entities, resulting in duplicated parent instances when multiple child entities exist.

Solution

To obtain distinct Order results even with FetchType.EAGER, Hibernate provides a workaround:

<code class="java">Collection result = new LinkedHashSet(session.createCriteria(...).list());</code>

This code snippet uses a LinkedHashSet to filter out duplicate Order references, ensuring that the result list only contains unique Order instances.

Alternatively, if the goal is to prevent join fetching entirely and stick with lazy loading, simply revert the FetchType setting back to FetchType.LAZY.

The above is the detailed content of Why Does Hibernate Criteria Return Multiple Copies of Children When Using 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