什么是 Hibernate 中的延迟加载? [英] What is lazy loading in Hibernate?

查看:26
本文介绍了什么是 Hibernate 中的延迟加载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java 中的延迟加载是什么?我不明白这个过程.有人能帮我理解延迟加载的过程吗?

What is lazy loading in Java? I don't understand the process. Can anybody help me to understand the process of lazy loading?

推荐答案

假设您有一个父级,并且该父级有一组子级.Hibernate 现在可以延迟加载"子级,这意味着在加载父级时它实际上并没有加载所有子级.相反,它会在请求时加载它们.您可以显式请求,或者更常见的是,当您尝试访问子项时,hibernate 会自动加载它们.

Say you have a parent and that parent has a collection of children. Hibernate now can "lazy-load" the children, which means that it does not actually load all the children when loading the parent. Instead, it loads them when requested to do so. You can either request this explicitly or, and this is far more common, hibernate will load them automatically when you try to access a child.

延迟加载有助于显着提高性能,因为通常您不需要孩子,因此它们不会被加载.

Lazy-loading can help improve the performance significantly since often you won't need the children and so they will not be loaded.

还要注意 n+1 问题.当您访问集合时,Hibernate 实际上不会加载所有子项.相反,它将单独加载每个孩子.在迭代集合时,这会导致对每个子项进行查询.为了避免这种情况,您可以欺骗 hibernate 同时加载所有孩子,例如通过调用 parent.getChildren().size().

Also beware of the n+1-problem. Hibernate will not actually load all children when you access the collection. Instead, it will load each child individually. When iterating over the collection, this causes a query for every child. In order to avoid this, you can trick hibernate into loading all children simultaneously, e.g. by calling parent.getChildren().size().

这篇关于什么是 Hibernate 中的延迟加载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆