How to fix org.hibernate.LazyInitializationException - could not initialize proxy - no Session

If you using Spring mark the class as @Transactional, then Spring will handle session management.

@Transactional
public class MyClass {
    ...
}

By using @Transactional, many important aspects such as transaction propagation are handled automatically. In this case if another transactional method is called the method will have the option of joining the ongoing transaction avoiding the "no session" exception.

WARNING If you do use @Transactional, please be aware of the resulting behavior. See this article for common pitfalls. For example, updates to entities are persisted even if you don't explicitly call save


You can try to set

<property name="hibernate.enable_lazy_load_no_trans">true</property>

in hibernate.cfg.xml or persistence.xml

The problem to keep in mind with this property are well explained here


What is wrong here is that your session management configuration is set to close session when you commit transaction. Check if you have something like:

<property name="current_session_context_class">thread</property>

in your configuration.

In order to overcome this problem you could change the configuration of session factory or open another session and only than ask for those lazy loaded objects. But what I would suggest here is to initialize this lazy collection in getModelByModelGroup itself and call:

Hibernate.initialize(subProcessModel.getElement());

when you are still in active session.

And one last thing. A friendly advice. You have something like this in your method:

for (Model m : modelList) {
    if (m.getModelType().getId() == 3) {
        model = m;
        break;
    }
}

Please insted of this code just filter those models with type id equal to 3 in the query statement just couple of lines above.

Some more reading:

session factory configuration

problem with closed session