This tutorial will teach you how to configure and optimize the fetch type strategy used in your Jakarta EE / Hibernate applications. In JPA terms, the FetchType strategy defines strategies for fetching data from the database.
The default FetchType depends on the cardinality of the relationship.
Here is a quick summary of defaults:
- OneToOne: EAGER
- ManyToOne: EAGER
- OneToMany: LAZY
- ManyToMany: LAZY
For example, consider the following Entity:
@Entity public class Customer implements Serializable { @ManyToOne private ItemOrder item; ... }
By default, when I fetch a Customer Entity with a @ManyToOne relation, the persistence provider will also fetch the related ItemOrder entity. This is the EAGER fetch strategy.
The EAGER strategy is a requirement on the persistence provider runtime that data must be eagerly fetched.
On the other hand, the ‘ LAZY strategy is a hint to the persistence provider runtime that data should be fetched lazily when it is first accessed.
If you want to override the default fetch type you can specify the fetch strategy with an annotation. Check the following example:
@Entity @Table(name = "PET") public class Pet implements Serializable { private long id; private Zoo zoo; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "ID") public long getId() { return id; } public void setId(long id) { this.id = id; } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "ZOO_ID") public Zoo getZoo() { return zoo; } public void setZoo(Zoo zoo) { this.zoo = zoo; } } @Entity @Table(name = "ZOO") public class Zoo implements Serializable { private long id; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "ID") public long getId() { return id; } public void setId(long id) { this.id = id; } }
Finally, consider that the fetch of data can also be influenced by other key factors, such as Fetch Join in your JPQL or the Criteria API. We recommend checking this tutorial to learn more about it:
Hibernate fetching performance tuning
Conclusion
We have covered the two ways to fetch data in Entity relations. Which one works the best? it depends on the usage of the Entity relation.
EAGER fetching can be very efficient because all Entities and their relations are fetched with only one query. But it can create a large overhead if your related Entities are large and not needed in all use cases.
LAZY fetching delays the initialization of the relationship until you are using the related Entity in your code. The drawback of this approach is that the JPA engine needs to execute an additional query to initialize each relationship.