lightyear
lightyear

Reputation: 21

LazyInitialization Hibernate

I am having this type of error. The reason for this was that since I am using sessionFactory beand and transactionmanager. Basically I googled and says set the column to FetchType.EAGER. But even though I did it, it is still showing the same error as if nothing happened. Please help.

Thank you

Error: org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.database.entity.User.roles, no session or session was closed

POJOS:
@OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER, mappedBy="user")
public Set<Role> getRoles() {
return this.roles;
}

Upvotes: 0

Views: 90

Answers (3)

Veena Nair
Veena Nair

Reputation: 101

May be in the Role side mapping you have mentioned LAZY and here you are mentioning EAGER. thats why it might be giving error. What I think, the actual solution for this would be .. give LAZY rather then giving EAGER and make use of Hibernate.initialize(yourset); in DAO implementation from where you want to load this set. in my case i was loading the set by using findById :

     @Override
    public Branch findByBranchId(Long id) {
            Branch branch=findById(id);
            Hibernate.initialize(branch);
            Hibernate.initialize(branch.getEmployeeSet());
            return branch;
       }

Hibernate.initialize(SetYouWantToFetch) will resolve you issue with Fetch Type : LAZY

Upvotes: 0

Samuar
Samuar

Reputation: 11

It could be a transaction issue. Mark up the method (or test) that is both fetching the User and examining its roles with the annotation @Transactional. After you retrieve the user, the database session is closed. So when you attempt to get the user's roles, you get the "no session or session was closed" error.

Providing a bit more information (e.g. the calling method code listing) is necessary to know for sure.

Upvotes: 1

Benoit Wickramarachi
Benoit Wickramarachi

Reputation: 6226

I would try to do Hibernate.initialize( pojo.getRoles() ); before closing the Hibernate session.

Upvotes: 0

Related Questions