Wednesday, January 2, 2019

Difference between fetch mode and fetch type in Hibernate.

FetchType (Lazy/Eager) instructs whether the entity to be loaded eagerly or lazy, when there is a call.
FetchMode (Select/Join) instructs whether the entitity to be loaded with additional select or in one query with join or subselect.

@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().

FetchMode (Select/Join) tells whether we want our entitity to be loaded with additional select or in one query with join or subselect.

Default fetch type for one-to-one, many-to-one and one-to-many in Hibernate

From the JPA 2.0 spec, the defaults are:
OneToMany: LAZY
ManyToOne: EAGER
ManyToMany: LAZY
OneToOne: EAGER
And in hibernate, all is Lazy

 

 

No comments:

Post a Comment

Spring Annotations