jpprade
jpprade

Reputation: 3674

Is there a solution to avoid LazyInitializationException

I am using spring 3.2 spring security and hibernate 3.4.0.

When my user login I store a User in my custom principal.

Later in the application I want to access a collection associated to my User. So I do :

User u = ((MyCustomPrincipal) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUser();
u.getMyCollection();

and I am getting of course a LazyInitException. So my temporary solution is to fetch again the user :

User u = ((MyCustomPrincipal) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUser();
u = userDao.find(u.getId());
u.getMyCollection();

by doing this it works but I feel that it is not a very optimized solution because my User ows 4 collections, so I wil be forced to fetch my user from db multiple time in diffent place (in my custom authenticator, in an interceptor, in my controller...).

Is there a solution to this problem like a global transaction or something ?

thanks

Upvotes: 1

Views: 344

Answers (2)

polypiel
polypiel

Reputation: 2341

You can try merging the detached user to the current session:

User u = ((MyCustomPrincipal) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUser();
u = userDao.merge(u);
u.getMyCollection();

http://docs.jboss.org/hibernate/entitymanager/3.4/reference/en/html/objectstate.html#d0e891

Upvotes: 1

Abhinav Sarkar
Abhinav Sarkar

Reputation: 23812

When my user login I store a User in my custom principal

At that point in your login code where you fetch the user from the userDao for the first time, just add the user.getMyCollection() call. This will fetch the associated collection and store it in the user object. When you access it later through the SecurityContextHolder, the LazyIntializationException will not be thrown.

Upvotes: 0

Related Questions