Skip to main content

r/SpringBoot



Simple, elevated rewards—with no category restrictions. Terms apply. Learn more about Venture X Business today.
media poster



Entity Relantionships - EAGER VS LAZY Entity Relantionships - EAGER VS LAZY
Question

Hi, everyone. I don't have too much experience, and I'd really appreciate your guidance on this

Based on your experience with Spring Boot and ORM, what fetch type would you recommend for a large project with many entities and numerous nested relationships?

I ALREADY KNOW THIS

  • Eager will fetch all data from all nested entities

  • Lazy just load on demand

  • I know that we must always return DTO's with only the necessary fields using SQL queries.

But when it comes to specifying the fetch type within a Java class, I'd like to know the best practice for specifying the fetch type:

Is it better to always set the relationship as LAZY and never use EAGER?

@type_of_relantionship(fetch = FetchType.LAZY)
private Entity myEntity; // it has nested entites
            |
            |          @type_of_relantionship(fetch = FetchType.LAZY) 
            |__________Entity subEntity 
                 
            //more relantionships...

vs 

@type_of_relantionship(fetch = FetchType.EAGER)
private Entity myEntity; // it has nested entites
            |
            |          @type_of_relantionship(fetch = FetchType.EAGER) 
            |__________Entity subEntity 
                 
            //more relantionships...

Thanks in advance