FetchMode 和 FetchType 的区别 [英] difference between FetchMode and FetchType
问题描述
指定 lazy = "true"
和使用 fetch = "select" 或 "join"
有什么区别?哪一个比另一个更受欢迎?
what is the difference in specifying lazy = "true"
and using fetch = "select" or "join"
? which one is preferred over the other ?
问候贾延德拉
推荐答案
假设我们有这样的实体:
Let's say we have entities like this:
@Entity
@Table
public class Parent {
@Id
private Long id;
@OneToMany(mappedBy="parent", fetch = FetchType.EAGER)
@Fetch(FetchMode.JOIN)
private List<Child> child;
//getter setters
}
@Entity
@Table
public class Child {
@Id
private Long id;
@ManyToOne(fetch = FetchType.LAZY)
private Parent parent;
//getter setter
}
在上面的例子中,当得到 Parent
实体时,hibernate 会使用 join 自动加载所有 child
实体.另一方面,当您获取 Child
时,不会选择 Parent
实体,除非您在代码 child.getParent()
.
In above example, when getting Parent
entity, hibernate will automaticly load all child
entities eagerly using join. On the other hand, when you fetch Child
, Parent
entity won't be selected unless you call it explicity in your code child.getParent()
.
FetchType (Lazy/Eager) 告诉我们在代码中有调用时是希望实体加载还是延迟加载.
FetchType (Lazy/Eager) tells whether we want entity to be loaded eagerly or lazy, when there's call in code.
FetchMode (Select/Join) 告诉我们是希望我们的实体加载额外的选择,还是在一个带有连接或子选择的查询中加载.
FetchMode (Select/Join) tells whether we want our entitity to be loaded with additional select or in one query with join or subselect.
这篇关于FetchMode 和 FetchType 的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!