Friday, June 22, 2012

Difference between FetchType LAZY and EAGER in Java persistence

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

No comments: