What is the difference between fetch="EAGER"
and fetch="LAZY"
in annotation @ManyToOne
in Doctrine ?
/** * @ManyToOne(targetEntity="Cart", cascade={"all"}, fetch="EAGER") */ /** * @ManyToOne(targetEntity="Cart", cascade={"all"}, fetch="LAZY") */
LAZY: It fetches the child entities lazily i.e at the time of fetching parent entity it just fetches proxy(created by cglib or any other utility) of the child entities and when you access any property of child entity then it is actually fetched by hibernate. EAGER: it fetches the child entities along with parent.
Eager fetching is the ability to efficiently load subclass data and related objects along with the base instances being queried.
LAZY – Fetch it when you need it. The FetchType. LAZY tells Hibernate to only fetch the related entities from the database when you use the relationship. This is a good idea in general because there's no reason to select entities you don't need for your uses case.
In Lazy loading, associated data loads only when we explicitly call getter or size method. In Eager loading, data loading happens at the time of their parent is fetched. 2. Default Strategy in ORM Layers. ManyToMany and OneToMany associations used lazy loading strategy by default.
To explain it simply, when you are loading an entity and if it has an association with one or more entities, what should doctrine do?
If the association is marked as EAGER, it will fetch and load the associated entity as well.
If the association is marked as LAZY, doctrine will create proxy objects (dummy objects) in place of the actual entity. Only when you make the first call to that associated entity (like $cart->getItems()
), doctrine will fetch and load that object(s) from database. (This is the default Behaviour)
Refer: https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/reference/advanced-configuration.html#association-proxies
Additional information about the difference between them:
(fetch = "EAGER")
the associated entities will be fetched as soon as the original query target entity is loaded from doctrine. That means there is no additional SQL query on DB.
(fetch = "LAZY")
the associated entities will be fetched ONLY IF the original query target entity calls the reference method, such as $cart->getItems()
. That means, there is additional
SQL query on DB.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With