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.
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.
Cascading and fetching are orthogonal concerns.
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.
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.
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