DEV Community

Cover image for Hibernate - EAGER fetching
Yiğit Erkal
Yiğit Erkal

Posted on • Edited on

Hibernate - EAGER fetching

EAGER fetching tells Hibernate to get the related entities with the initial query. This can be very efficient because all entities are fetched with only one query. But in most cases it just creates a huge overhead because you select entities you don't need in your use case.

Here is an example why you may not need EAGER as fetching type. A basic class tells that an EagerCompany has multiple EagerProducts. The default FetchType is LAZY. However, the coder overwrite the fetch type as EAGER.

@Entity
@Table(name='companies')
public class EagerCompany { 
  @Id
  private int id;
  private String name;

  @OneToMany(fetch = FetchType.EAGER, mappedBy = 'company')
  private Set<EagerProducts> products = new HashSet<>();
}
Enter fullscreen mode Exit fullscreen mode

To observe what is running on the background, coder has implemented a basic method.

@Transactional
public int countProductsByCompany(int id) {
  EagerCompany company = entityManager.find(EagerCompany.class, id);
  return company.getProducts().size();
}
Enter fullscreen mode Exit fullscreen mode

The output of Hibernate query is:

Hibernate:
select eagercompa0_.id as id1_0_0_,
eagercompa0_.name as name2_0_0_,
products1_.company_id as company_3_1_1_,
productsl_.id as id1_1_1_,
productsl_.id as id1_1_2_,
products1_.company_id as company_3_1_2_,
products1_.stock as stock2_1_2_
from
companies eagercompa0_
left outer join
products products1_
on
eagercompa0_.id = products1_.company_id
where
eagercompa0_.id=?

In eager loading strategy, if we load the Company data, it will also load up all Products associated with it and will store it in a memory.

The EAGER product association was retrieved using an left join. All the relative associations fetched as well. For M such associations the owner entity table is going to be joined M times.

Each extra join adds up to the overall query complexity and execution time. If we don’t even use all these associations, for every possible business scenario, then we’ve just paid the extra performance penalty for nothing in return.

To sum up,

Advantages:

  • No delayed initialization-related performance impacts

Disadvantages:

  • Long initial loading time
  • Loading too much unnecessary data might impact performance

Top comments (0)