Hibernate fetching strategies

WHEN (fetch timing) and HOW (fetch style)

Jun 4, 2021 | - views

We wanna talk about fetching strategies. All the time we will decide when data will fetch and how it will be fetched.

When

EAGER. In this case data will be delivered immediately. So we no need extra fetch for get this data but payload can be significantly large.

@OneToOne(fetch = FetchType.EAGER)
private MyEntity entity;

LAZY. In this case data will be delivered when it is necessary. So we need extra fetch for get this data. Collection is lazy by default because list can we large.

@OneToMany(fetch = FetchType.LAZY)
private List<MyEntity> entities;

How

JOIN. Join fetch (left/outer join). This is great for to one associations.

select e from MyEntity e
join fetch e.subEntities p
where p.id = 42

SELECT. Follow-up selects. This is default style for collections.

select e from MyEntity e where e.id = 42

BATCH. Fetches multiples entries when one is accessed.

@OneToMany
@BatchSize(size = 5)
List<MyEntity> entities;

Related articles: