Member-only story

Fetching strategies in Hibernate

Namrata
5 min readMar 3, 2024

--

In Hibernate, fetching refers to the strategy used to retrieve associated objects from the database when querying for a particular entity.

There are different fetching strategies such as eager fetching and lazy fetching. Eager fetching retrieves the associated objects along with the main entity in a single query, while lazy fetching defers the retrieval of associated objects until they are explicitly accessed.

Choosing the right fetching strategy is important for optimizing performance and managing the retrieval of related data in Hibernate.

There are two major fetching type.

Lazy Fetching

This is the default fetching strategy in Hibernate. When you load a parent entity, the child entities are not loaded into memory. Instead, a proxy is set up and the child entities are only loaded when they are actually accessed in the code. This can be very useful for performance when you have a large number of child entities, and you don’t need to access them every time you load the parent.

This is the default for @OneToMany and @ManyToMany relationships.

@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

@OneToMany(fetch = FetchType.LAZY)
private List<Order> orders;
}

Here have a User entity and each User can have multiple Order entities. If you load a User, but you don't need to look at their Orders right away…

--

--

Namrata
Namrata

Written by Namrata

Engineering @Microsoft A software developer writing her daily bits . https://www.linkedin.com/in/namrataagarwal5/

No responses yet