What is the difference between FetchType.LAZY and FetchType.EAGER in Java Persistence API?
What is the difference between FetchType.LAZY and FetchType.EAGER in Java Persistence API?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Sometimes you have two entities and there’s a relationship between them. For example, you might have an entity called
Universityand another entity calledStudentand 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:
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:
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
studentsis explicitly marked to be loaded eagerly:And here’s an example where
studentsis explicitly marked to be loaded lazily: