Skip to content
Advertisement

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

In the custom AuthenticationProvider from my spring project, I am trying read the list of authorities of the logged user, but I am facing the following error:

JavaScript

Reading other topics from here in StackOverflow, I understand this happens due the way this type of atribute is handled by the framework, but i can’t figure out any solution for my case. Someone can point what i am doing wrong and what I can do to fix it?

The code of my Custom AuthenticationProvider is:

JavaScript

My Entity classes are:

UsuarioHome.java

JavaScript

AutorizacoesUsuario.java

JavaScript

Autorizacoes.java

JavaScript

Full project available on github

–> https://github.com/klebermo/webapp_horario_livre

Advertisement

Answer

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

JavaScript

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

JavaScript

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

JavaScript

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.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement