Eugene Cuz Eugene Cuz - 2 months ago 14
MySQL Question

Does eager loading load all related objects?

Say I have 3 entities

class User{
int idUser;
List<Story> stories;
}

class Story{
int idStory;
User idUser;
List<Comment> comments;
}

class Comment{
int idComment;
Story idStory;
}


If I wanted to display all users on screen and if all this objects loaded eagerly, would it mean that upon loading each user I'll first load all the stories he has written and when loading each story I'll load all comments posted for it and so on?

Or would it just stop at loading stories?

Answer

Hibernate will do fetching exactly like you define it.

Let's say that:

class User{
  int idUser;
  @OneToMany(fetch = FetchType.EAGER)
  List<Story> stories;
}

class Story{
  int idStory;
  User idUser;
  @OneToMany(fetch = FetchType.EAGER)
  List<Comment> comments;
}

So, when we'll try to load User entity we'll also be fetching all related Story entities because the association on User class is set to fetch eagerly.

Also, while hibernate will fetch Story entities (because what mention earlier) we'll also fetch all related Comment entities, again, because the association on Story class is set to fetch eagerly.

That will be executed when will try to load a single User.

However, if instead of we had defined:

class Story{
  int idStory;
  User idUser;
  @OneToMany(fetch = FetchType.Lazy)
  List<Comment> comments;
}

then when we'll try to fetch a User entity, we'll only fetch eagerly the Story entities, and not continue to try to fetch Comment entities because it is has a lazy fetch.

In this case, we'll fetch the Comment entities when we'll try to access it.