FetchType的区别是什么。LAZY和FetchType。Java持久性API中的EAGER ?


当前回答

I may consider performance and memory utilization. One big difference is that EAGER fetch strategy allows to use fetched data object without session. Why? All data is fetched when eager marked data in the object when session is connected. However, in case of lazy loading strategy, lazy loading marked object does not retrieve data if session is disconnected (after session.close() statement). All that can be made by hibernate proxy. Eager strategy lets data to be still available after closing session.

其他回答

默认情况下,对于所有的集合和映射对象,获取规则是FetchType。LAZY,对于其他实例,它遵循FetchType。急切的政策。 简而言之,@OneToMany和@ManyToMany关系并不隐式地获取相关对象(集合和映射),但检索操作通过@OneToOne和@ManyToOne中的字段级联。

(提供:- objectdbcom)

如果你在使用Hibernate,你可以在调用getStudents()方法时调用Hibernate.initialize():

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

这两种类型的抓取之间的主要区别是数据加载到内存中的时刻。 我附上了2张照片来帮助你理解这一点。

急于获取

延迟获取

I may consider performance and memory utilization. One big difference is that EAGER fetch strategy allows to use fetched data object without session. Why? All data is fetched when eager marked data in the object when session is connected. However, in case of lazy loading strategy, lazy loading marked object does not retrieve data if session is disconnected (after session.close() statement). All that can be made by hibernate proxy. Eager strategy lets data to be still available after closing session.

对集合的EAGER加载意味着在获取它们的父类时,它们被完全获取。如果你有课程并且它有List<Student>,所有的学生在课程被获取的同时从数据库中获取。

另一方面,LAZY意味着只有当您试图访问List的内容时才会获取它们。例如,调用course.getStudents().iterator()。调用List上的任何访问方法都将启动对数据库的调用以检索元素。这是通过围绕列表(或集合)创建代理来实现的。所以对于惰性集合,具体的类型不是ArrayList和HashSet,而是PersistentSet和PersistentList(或PersistentBag)。