开发者

Is it possible to use lazy loading with many to many relation in hibernate?

开发者 https://www.devze.com 2023-04-12 15:50 出处:网络
hi i have two entities User and Authority they have many to many relation: @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)

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") }, inverseJoinColu开发者_StackOverflow社区mns = { @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 ?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号