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 :

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
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With