Reputation: 1385
what is the difference in specifying lazy = "true"
and using fetch = "select" or "join"
? which one is preferred over the other ?
regards jayendra
Upvotes: 39
Views: 42652
Reputation: 3522
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
}
In the example above, when getting Parent
entity, hibernate will automatically 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 explicitly in your code child.getParent()
.
FetchType (Lazy/Eager) tells whether we want entity to be loaded eagerly or lazy, when there's call in code.
FetchMode (Select/Join) tells whether we want our entity to be loaded with additional select or in one query with join or subselect.
Upvotes: 44
Reputation: 4973
FetchMode : It defines how
hibernate (using which strategy, e.g. Join, SubQuery etc) will fetch data from database.
FetchType : It defines whether
hibernate will fetch the data or not.
FetchMode
isn't only applicable with FetchType.EAGER
. The rules are as follows: a) if you don't specify FetchMode
, the default is JOIN
and FetchType
works normal, b) if you specify FetchMode.JOIN
explicitly, FetchType
is ignored and a query is always eager, c) if you specify FetchMode.SELECT
or FetchMode.SUBSELECT
, FetchType.Type
works normal
Upvotes: 34