Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is difference between Hibernate EAGER fetch and cascade-type all

Please explain difference between hibernate Eager fetching and cascade-type all.

In both configuration we can load child object associated with its parent, then what is difference between in.

like image 228
sagar narkhede Avatar asked Dec 24 '22 19:12

sagar narkhede


2 Answers

Its simple :Consider two entities 1. Department and 2. Employee and they have one-to-many mappings.That is one department can have many employee cascade=CascadeType.ALL and it essentially means that any change happened on DepartmentEntity must cascade to EmployeeEntity as well. If you save an Department , then all associated Employee will also be saved into database. If you delete an Department then all Employee associated with that Department also be deleted.
Cascade-type all is combination of PERSIST, REMOVE ,MERGE and REFRESH cascade types. Example for Cascade type All

Fetch type Eager is essentially the opposite of Lazy.Lazy which is the default fetch type for all Hibernate annotation relationships. When you use the Lazy fetch type, Hibernate won’t load the relationships for that particular object instance. Eager will by default load ALL of the relationships related to a particular object loaded by Hibernate.Click here for an example.

like image 63
Viraj Nalawade Avatar answered Dec 30 '22 12:12

Viraj Nalawade


Cascading and fetching are orthogonal concerns.

  1. Cascading is about propagating an entity state transition from a Parent entity to a Child, simplifying the data access code by allowing the ORM tool to persist/merge/remove dependent associations on out behalf.

  2. EAGER fetching is a mapping-time association loading decision, because it instructs Hibernate to always retrieve depended associations whenever a root entity gets loaded. Query-time fetching is preferred, because it gives you better flexibility and while the LAZY fetching mapping policy can be overridden by the FETCH directive. With EAGER fetching your are stuck, because you can't override it at query time and Hibernate will always fetch the association, even if on some use cases you don't need it.

like image 36
Vlad Mihalcea Avatar answered Dec 30 '22 11:12

Vlad Mihalcea