Difference between FetchType LAZY and EAGER in Java persistence?

I am a newbie to Java persistence and Hibernate.

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

asked Jun 30, 2015 in hibernate by rahulgii
0 votes

1 Answer

0 votes

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.

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

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.

answered Jun 30, 2015 by rahulgii