Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

How do I fix org.hibernate.LazyInitializationException?

See log detailed error below: org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.teamtreehouse.giflib.model.Category.gifs, could not initialize proxy - no Session

1 Answer

When you have a parent entity (Category) with associated entities (Gifs), there are two ways for Hibernate to deal with the relationship:

  • Eager loading (every time you retrieve a category, hibernate also retrieves ALL associated gifs from the database)
  • Lazy loading (by default Hibernate does not retrieve the associated gifs when a category is retrieved. You must do it explicitly when you need the gif entities)

Opting for eager loading is the easiest way to solve this. But in a real app it's terrible. Imagine you display a list of all categories: with eager loading, Hibernate also loads every single gif in the database associated with one of those categories. Even though you don't need the gifs right now. It doesn't matter in a treehouse project, you don't have much data anyway. In real life it leads to a slow, slow app.

So it's better practice to use lazy loading and initialize the relationship when needed. For example in your CategoryDao you would load a single category with its associated gifs like that:

    @Override
    public Category findById(Long id) {
        Session session = sessionFactory.openSession();
        Category category = session.get(Category.class,id);
        //with this line, you load the gif entities when you find a category by id
        Hibernate.initialize(category.getGifs());  
        session.close();
        return category;
    }

To learn more about this:

Thanks! Well said.