Difference between FetchType LAZY and EAGER in Java Persistence API?

后端 未结 15 993
鱼传尺愫
鱼传尺愫 2020-11-22 08:08

I am a newbie to Java Persistence API and Hibernate.

What is the difference between FetchType.LAZY and FetchType.EAGER in Java Persistence API?

相关标签:
15条回答
  • 2020-11-22 09:01

    LAZY: It fetches the child entities lazily i.e at the time of fetching parent entity it just fetches proxy(created by cglib or any other utility) of the child entities and when you access any property of child entity then it is actually fetched by hibernate.

    EAGER: it fetches the child entities along with parent.

    For better understanding go to Jboss documentation or you can use hibernate.show_sql=true for your app and check the queries issued by the hibernate.

    0 讨论(0)
  • 2020-11-22 09:04

    The main difference between the two types of fetching is a moment when data gets loaded into a memory.
    I have attached 2 photos to help you understand this.

    Eager fetch

    Lazy fetch

    0 讨论(0)
  • 2020-11-22 09:04

    @drop-shadow if you're using Hibernate, you can call Hibernate.initialize() when you invoke the getStudents() method:

    Public class UniversityDaoImpl extends GenericDaoHibernate<University, Integer> implements UniversityDao {
        //...
        @Override
        public University get(final Integer id) {
            Query query = getQuery("from University u where idUniversity=:id").setParameter("id", id).setMaxResults(1).setFetchSize(1);
            University university = (University) query.uniqueResult();
            ***Hibernate.initialize(university.getStudents());***
            return university;
        }
        //...
    }
    
    0 讨论(0)
提交回复
热议问题