difference between FetchMode and FetchType
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 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) 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 entitity to be loaded with additional select or in one query with join or subselect.
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.
UPDATES (as per suggestions from comments)
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