WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Spring Boot & Hibernate · Intermediate · question 26 of 100

What are the differences between FetchType.LAZY and FetchType.EAGER in Hibernate?

📕 Buy this interview preparation book: 100 Spring Boot & Hibernate questions & answers — PDF + EPUB for $5

In Hibernate, FetchType is an enumeration that determines how an association between entities should be fetched from the database. There are two possible values for FetchType: LAZY and EAGER.

FetchType.LAZY: When FetchType.LAZY is used, the associated entity will not be fetched from the database until it is explicitly requested. This means that if the associated entity is not accessed, it will not be loaded from the database, which can save resources and improve performance. For example:

    @ManyToOne(fetch = FetchType.LAZY)
    private Book book;

In this example, the book entity is associated with another entity using a ManyToOne mapping, and the fetch attribute is set to FetchType.LAZY. This means that the book entity will not be loaded from the database until it is explicitly accessed.

FetchType.EAGER: When FetchType.EAGER is used, the associated entity will be fetched from the database immediately when the owning entity is loaded. This means that if the associated entity is not accessed, it will still be loaded from the database, which can result in unnecessary overhead and reduced performance. For example:

    @ManyToOne(fetch = FetchType.EAGER)
    private Book book;

In this example, the book entity is associated with another entity using a ManyToOne mapping, and the fetch attribute is set to FetchType.EAGER. This means that the book entity will be loaded from the database immediately when the owning entity is loaded.

In general, it is recommended to use FetchType.LAZY for associations that are not frequently accessed or where loading the associated entity would cause significant overhead. This can help improve performance and reduce resource usage. On the other hand, FetchType.EAGER should be used for associations that are frequently accessed or where loading the associated entity is required for the operation of the owning entity.

It is also worth noting that the default value for FetchType is EAGER. This means that if the fetch attribute is not explicitly set, Hibernate will assume that FetchType.EAGER should be used. Developers should be careful to explicitly set FetchType to LAZY for associations that should be lazily fetched.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Spring Boot & Hibernate interview — then scores it.
📞 Practice Spring Boot & Hibernate — free 15 min
📕 Buy this interview preparation book: 100 Spring Boot & Hibernate questions & answers — PDF + EPUB for $5

All 100 Spring Boot & Hibernate questions · All topics