views:

69

answers:

4

Hi I am a newbie to Java persistence and Hibernate.

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

Thanks

+1  A: 

Basically,

LAZY = fetch when needed
EAGER = fetch immediately
unbeli
A: 

From the Javadoc:

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.

E.g., eager is more proactive than lazy. Lazy only happens on first use (if the provider takes the hint), whereas with eager things (may) get pre-fetched.

T.J. Crowder
what do you mean by "first use"?
leon
@leon: Say you have an entity with an eager field and a lazy field. When you get the entity, the eager field will have been loaded from the DB by the time you receive the entity reference, but the lazy field may not have been. It would be fetched only when you tried to *access* the field via its accessor.
T.J. Crowder
+3  A: 

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.

Bytecode Ninja
Thanks!! I understand it now.
leon
You're welcome. :)
Bytecode Ninja
A: 

EAGER loading of collections means that they are fetched fully at the time their parent is fetched. So if you have Course and it has List<Student>, all the students are fetched from the database at the time the Course is fetched.

LAZY on the other hand means that the contents of the List are fetched only when you try to access them. For example, by calling course.getStudents().iterator(). Calling any access method on the List will initiate a call to the database to retrieve the elements. This is implemented by creating a Proxy around the List (or Set). So for your lazy collections, the concrete types are not ArrayList and HashSet, but PersistentSet and PersistentList (or PersistentBag)

Bozho