Hibernate EAGER fetch 和 cascade-type all 有什么区别

2022-01-20 00:00:00 orm fetch java Hibernate jpa

请解释一下hibernate Eager fetching和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.

推荐答案

很简单:考虑两个实体 1. Department 和 2. Employee ,它们有一对多的映射关系.即一个部门可以有多个员工cascade=CascadeType.ALL,它本质上意味着 DepartmentEntity 上发生的任何更改也必须级联到 EmployeeEntity.如果您保存一个 Department ,那么所有关联的 Employee 也将被保存到数据库中.如果您删除一个部门,则与该部门关联的所有员工也将被删除.
级联类型都是 PERSIST、REMOVE、MERGE 和 REFRESH 级联类型的组合. 级联类型全部示例

获取类型 Eager 本质上与 Lazy.Lazy 相反,后者是所有 Hibernate 注释关系的默认获取类型.当您使用 Lazy fetch 类型时,Hibernate 不会加载该特定对象实例的关系.Eager 默认会加载与 Hibernate 加载的特定对象相关的所有关系.点击此处查看示例.

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.

相关文章