difference between FetchMode and FetchType

后端 未结 2 1706
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-24 05:52

what is the difference in specifying lazy = \"true\" and using fetch = \"select\" or \"join\" ? which one is preferred over the other ?

2条回答
  •  不知归路
    2020-12-24 06:46

    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;    
        //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.

提交回复
热议问题