Himai Minh wrote:I am not too familiar with FetchMode. But you may find a clue : https://www.baeldung.com/hibernate-fetchmode
The 5-second intro to FetchMode (NOTE Hibernate and JPA are NOT always the same thing!!!)
FetchMode controls how related objects are fetched from the database when you fetch an Entity object.
EAGER fetch means then if I have an Invoice Entity and a bunch of InvoiceItems (collection) and I fetch the Invoice, the InvoiceItems get fetched at the same time.
LAZY fetch means that if I fetch the Invoice, the InvoiceItems do NOT get fetched. Only if I explicitly access the InvoiceItems collection will cause them to be fetched. That means I can save time and resources if I want only the Invoice and not its line items. It also means that I avoid the dread "vacuum" effect that I'll explain in a moment.
The biggest "gotcha" to LAZY fetch comes when you fetch the Invoice and then DETACH it from its EntityManager. This is a useful thing to do, since it converts the Entity instance into a POJO that isn't secretly dragging around a lot of data management stuff with it, but the downside of not having that secret management stuff is that any attempt to access InvoiceItems will throw an Exception because the database cannot be accessed. The Proxy Object ensures that so that we can tell non-fetched data from non-existent data (that is, if there ARE no InvoiceItems).
To avoid that Exception, the Entity must first be re-attached (merged) and then you can access InvoiceItems in the normal way.
OK, to wrap it up, aside from the memory/CPU overhead, there's another disadvantage to EAGER fetching. If the dependent objects refer in turn to other objects and those references are
also EAGER, then they get piggybacked in automatically (the "vaduum effect"). In some cases, a simple one-record fetch can end up pulling the entirety of a very large database into RAM.
Which is why it's useful to have a choice of fetch options, even though it does make things slightly more complicated.