Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix Hibernate LazyInitializationException: failed to lazily initialize a collection of roles, could not initialize proxy - no Session

People also ask

How do you fix org hibernate LazyInitializationException could not initialize proxy no session?

if you are using annotation configuration: add @Proxy(lazy=false) to all your entity classes. That's all about how to fix Exception in thread "main" org. hibernate. LazyInitializationException: could not initialize proxy - no Session.


You need to either add fetch=FetchType.EAGER inside your ManyToMany annotations to automatically pull back child entities:

@ManyToMany(fetch = FetchType.EAGER)

A better option would be to implement a spring transactionManager by adding the following to your spring configuration file:

<bean id="transactionManager"
    class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory" />
</bean>

<tx:annotation-driven />

You can then add an @Transactional annotation to your authenticate method like so:

@Transactional
public Authentication authenticate(Authentication authentication)

This will then start a db transaction for the duration of the authenticate method allowing any lazy collection to be retrieved from the db as and when you try to use them.


The best way to handle the LazyInitializationException is to use the JOIN FETCH directive for all the entities that you need to fetch along.

Anyway, DO NOT use the following Anti-Patterns as suggested by some of the answers:

  • Open Session in View
  • hibernate.enable_lazy_load_no_trans

Sometimes, a DTO projection is a better choice than fetching entities, and this way, you won't get any LazyInitializationException.


Adding following property to your persistence.xml may solve your problem temporarily

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

As @vlad-mihalcea said it's an antipattern and does not solve lazy initialization issue completely, initialize your associations before closing transaction and use DTOs instead.


I too had this problem when I was doing unit Testing. A very Simple Solution to this problem is to use @Transactional annotation which keeps the session open till the end of the execution.