j will
j will

Reputation: 3807

Hibernate Object Eagerly Loads Lazy Collection

enter image description hereI have a hibernate entity object call project and it has two collections in it called notes and messages like so:

@Entity
@Table(name = "project")
public class Project {
    ...
    @OneToMany(fetch = FetchType.LAZY, mappedBy = "project")
    private List<Note> notes;
    @OneToMany(fetch = FetchType.LAZY, mappedBy = "project")
    private List<Message> messages;
    ...
}

But for some reason in my test method for getting a project, the notes and messages are already loaded, and my test verifies that:

@Test
public void testLoadProjectNotes() {
    Project project = projectDao.getProjectById(41);
    assertNotNull(project.getNotes().get(0));

}

I thought a problem could be that I am getting the notes and causing hibernate to load them into the project. Before I execute that statement, though, the debugger shows the notes in the project, before I get the notes.

Here is the method for getting the project by the id:

public Project getProjectById(long id) {
    Criteria criteria = new SmartCriteria(getSession().createCriteria(Project.class));
    criteria.add(Restrictions.eq("id", id));
    return (Project) criteria.uniqueResult();
}

So nowhere in the method for getting the project by its id am I getting the results of the notes and the messages.

How do I ensure that the collections I want lazily loaded are being loaded lazily?

Upvotes: 3

Views: 900

Answers (2)

j will
j will

Reputation: 3807

So I figured it out, when I open the display on the project variable and click on notes or messages, eclipse is calling getNotes and getMessages on the project and thus dynamically loading the notes and messages from the database.

Upvotes: 0

dunni
dunni

Reputation: 44555

As soon as you call the getter, a lazy loaded collection is initialized. So that statement is by far not usable to detect, if a collection is lazy loaded. If you want to check that, use the method Hibernate.isInitialized(project.getNotes()).

Upvotes: 8

Related Questions