Java持久性API中的FetchType LAZY和EAGER之间的区别? [英] Difference between FetchType LAZY and EAGER in Java Persistence API?

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

问题描述

我是Java持久性API和Hibernate的新手。

I am a newbie to Java Persistence API and Hibernate.

FetchType.LAZY FetchType.EAGER

推荐答案

有时你有两个实体,它们之间存在关系。例如,您可能有一个名为University的实体和另一个名为Student的实体。

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.

大学实体可能具有一些基本属性,例如id,名称,地址等以及一个名为学生的财产:

The University entity might have some basic properties such as id, name, address, etc. as well as a property called students:

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

 // setters and getters
}

现在当你从数据库加载大学,JPA会为您加载其ID,名称和地址字段。但是,对于学生来说,您有两种选择:在您调用大学的getStudents()方法时,将其与其他字段(即急切地)一起加载或按需加载(即,懒惰地)。

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 students: to load it together with the rest of the fields (i.e. eagerly) or 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 with it when they are not needed. So in suchlike cases, you can declare that you want students to be loaded when they are actually needed. This is called lazy loading.

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

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