Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate : failed to lazily initialize a collection

I have two entities : User and Module wich are linked using the many-to-many .

in my User entity I have a Module list member :

enter image description here

I insert a new user successfully, but when I want to retrieve the Users I get the Users informations but I don't get the Modules of a user . and I get this error message :

.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: ma.propar.FireApp.Entites.Utilisateur.modules, could not initialize proxy - no Session

like image 495
Abdessamad BOUTGAYOUT Avatar asked Dec 05 '25 14:12

Abdessamad BOUTGAYOUT


2 Answers

The user.modules @ManyToMany list is LAZY by default, so when you fetch users you only get a user.modules proxy.

If the Hibernate Session is closed, you won't be able to access the uninitialized proxies without getting a LazyInitializationException.

To fetch modules in the same HQL query you need to use "fetch":

select u from Utilisateur u left join fetch u.modules

Although you can set the association to FetchType.EAGER so that you always retrieve modules along Users

@ManyToMany(fetch=FetchType.EAGER)

you shouldn't use EAGER because it's bad for performance.

like image 200
Vlad Mihalcea Avatar answered Dec 07 '25 03:12

Vlad Mihalcea


To piggyback on Vlad's answer, with annotations you can implement fetch with

import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
@ManyToMany(cascade = CascadeType.ALL,fetch=FetchType.EAGER)
@Fetch(FetchMode.SELECT)
like image 25
Bobby King Avatar answered Dec 07 '25 02:12

Bobby King