2

hi i have two entities User and Authority they have many to many relation:

@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    @JoinTable(name = "user_role", joinColumns = { @JoinColumn(name = "user_id") }, inverseJoinColumns = { @JoinColumn(name = "authority_id") })
    private List<Authority> authorities = new ArrayList<Authority>(0);

when i use FetchType.LAZY and try to get the authorities in user i get the exception:

org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role

here's how i get the user object:

public UserDetails loadUserByUsername(String username)
            throws UsernameNotFoundException, DataAccessException {
        User user = userDao.findUserByEmail(username);
        if (user == null)
            throw new UsernameNotFoundException("No user with username '"
                    + username + "' found!");
        return new org.springframework.security.core.userdetails.User(
                user.getEmail(), user.getPassword(), true, true, true, true,
                setUserAuthorities(user.getAuthorities()));
    }

i am using session factory to manage my transactions and @Transactional on the dao method. so is there's any ideas or solutions for this issue ?

1 Answer 1

1

Yes, this is one of the most common exceptions. It means your session is closed at the time you try to read your collection.

The solution is to have an option session. Or to initialize the collection before having the session closed.

Btw, don't put @Transactional in the dao layer. Ideally it should be on the service layer.

Sign up to request clarification or add additional context in comments.

7 Comments

is there is any samples for the two solutions you mentioned, and i updated my question so you can understand the case.
Google for OpenSessionInView. Or make the collection eager - it's a small one, so it won't be a problem
so OpenSessionInView will be the solution if the collection is big, right ? coz i have other many to many relation between authority and permission, and one authority will have lots of permissions so eager will be an overhead here, and it must be lazy.
and what do you think about this tutorial: cchweblog.wordpress.com/2009/10/10/…
can you please suggest a good tutorial or links for using OpenSessionInView ?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.