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


当前回答

据我所知,这两种类型的取回取决于你的要求。

FetchType。LAZY是按需的(即当我们需要数据时)。

FetchType。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.

public enum FetchType extends java.lang.Enum Defines strategies for fetching data from the database. The EAGER strategy is a requirement on the persistence provider runtime that data must be eagerly fetched. The LAZY strategy is a hint to the persistence provider runtime that data should be fetched lazily when it is first accessed. The implementation is permitted to eagerly fetch data for which the LAZY strategy hint has been specified. Example: @Basic(fetch=LAZY) protected String getName() { return name; }

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

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

有时你有两个实体它们之间有关系。例如,你可能有一个实体叫University,另一个实体叫Student,一个University可能有很多Student:

University实体可能有一些基本属性,如id、名称、地址等,以及一个名为students的集合属性,它返回给定大学的学生列表:

public class University {
   private String id;
   private String name;
   private String address;
   private List<Student> students;

   // setters and getters
}

现在,当您从数据库加载University时,JPA将为您加载它的id、名称和地址字段。但是你有两种选择:

将它与其他字段一起加载(即急切地加载),或者 在调用大学的getStudents()方法时按需加载它(即惰性加载)。

当一所大学有很多学生时,加载所有的学生并不是有效的,特别是当他们不需要的时候,在这种情况下,你可以声明你想要在实际需要学生的时候加载他们。这被称为惰性加载。

下面是一个例子,学生被明确地标记为急切加载:

@Entity
public class University {

    @Id
    private String id;

    private String name;

    private String address;

    @OneToMany(fetch = FetchType.EAGER)
    private List<Student> students;

    // etc.    
}

这里有一个例子,学生被明确地标记为惰性加载:

@Entity
public class University {

    @Id
    private String id;

    private String name;

    private String address;

    @OneToMany(fetch = FetchType.LAZY)
    private List<Student> students;

    // etc.
}

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

急于获取

延迟获取