Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between fetch="EAGER" and fetch="LAZY" in doctrine

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")  */ 
like image 530
Mohamed Ben HEnda Avatar asked Nov 12 '14 16:11

Mohamed Ben HEnda


People also ask

What is the difference between fetch type eager and 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.

What is fetch eager?

Eager fetching is the ability to efficiently load subclass data and related objects along with the base instances being queried.

What is fetch FetchType lazy?

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.

What is eager fetch and lazy loading in hibernate?

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.


2 Answers

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

like image 125
Pradeep Avatar answered Oct 19 '22 14:10

Pradeep


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.

like image 45
vikbert Avatar answered Oct 19 '22 14:10

vikbert