Java Persistence API 中 FetchType LAZY 和 EAGER 的区别? [英] Difference between FetchType LAZY and EAGER in Java Persistence API?

查看:25
本文介绍了Java Persistence API 中 FetchType LAZY 和 EAGER 的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Java Persistence API 和 Hibernate 的新手.

公开课大学{私人字符串ID;私人字符串名称;私有字符串地址;私人名单<学生>学生们;//setter 和 getter}

现在,当您从数据库加载大学时,JPA 会为您加载其 ID、名称和地址字段.但是对于如何加载学生,您有两种选择:

  1. 将它与其他字段一起加载(即热切地),或
  2. 在您调用大学的 getStudents() 方法时按需加载(即延迟加载).

当一所大学有很多学生时,将所有学生一起加载是效率低下的,尤其是当他们不需要时,在这种情况下,您可以声明希望在实际需要时加载学生.这称为延迟加载.

这是一个示例,其中 students 被明确标记为急切加载:

@Entity公开课大学{@ID私人字符串ID;私人字符串名称;私有字符串地址;@OneToMany(fetch = FetchType.EAGER)私人名单<学生>学生们;//等等.}

这里有一个例子,其中 students 被明确标记为延迟加载:

@Entity公开课大学{@ID私人字符串ID;私人字符串名称;私有字符串地址;@OneToMany(fetch = FetchType.LAZY)私人名单<学生>学生们;//等等.}

I am a newbie to Java Persistence API and Hibernate.

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

解决方案

Sometimes you have two entities and there's a relationship between them. For example, you might have an entity called University and another entity called Student and a University might have many Students:

The University entity might have some basic properties such as id, name, address, etc. as well as a collection property called students that returns the list of students for a given university:

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

   // setters and getters
}

Now when you load a University from the database, JPA loads its id, name, and address fields for you. But you have two options for how students should be loaded:

  1. To load it together with the rest of the fields (i.e. eagerly), or
  2. To load it on-demand (i.e. lazily) when you call the university's getStudents() method.

When a university has many students it is not efficient to load all of its students together with it, especially when they are not needed and in suchlike cases you can declare that you want students to be loaded when they are actually needed. This is called lazy loading.

Here's an example, where students is explicitly marked to be loaded eagerly:

@Entity
public class University {

    @Id
    private String id;

    private String name;

    private String address;

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

    // etc.    
}

And here's an example where students is explicitly marked to be loaded lazily:

@Entity
public class University {

    @Id
    private String id;

    private String name;

    private String address;

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

    // etc.
}

这篇关于Java Persistence API 中 FetchType LAZY 和 EAGER 的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆