0

I know this question has been asked a lot, but I couldn't find a way to fix my problem. So I have have a managed bean called CurrentUser, which holds a Users instance, upon logging, I save the current logged in user in that instance, here is the login method:

public static Users login(String username, String password) {

    Session session = HibernateUtil.getSessionFactory().openSession();
    session.getTransaction().begin();

    try {
        Criteria criteria = session.createCriteria(Users.class);

        criteria.add(Restrictions.eq("username", username));
        criteria.add(Restrictions.eq("password", password));
        List<Users> list = criteria.list();

        try {
            session.getTransaction().commit();
        } catch (Exception e) {
            e.printStackTrace();
            session.getTransaction().rollback();
        } finally {
            if (session.isOpen()) {
                session.close();
            }
        }

        if (list.isEmpty()) {
            return null;
        } else {
            new Logs(null, "Logging in", "/login.xhtml", "", list.get(0)).add();
            return list.get(0);
        }
    } catch (Exception e) {
        e.printStackTrace();
        session.getTransaction().rollback();
        if (session.isOpen()) {
            session.close();
        }
        return null;
    }
}

So this user have a collection of expertise lazily mapped:

@OneToMany(mappedBy = "user")
@NotFound(action = NotFoundAction.IGNORE)
@Cascade({org.hibernate.annotations.CascadeType.REPLICATE, CascadeType.SAVE_UPDATE, CascadeType.MERGE})
private List<Expertise> expertises;

In another managed bean, I have injected the currentUser instance, but when I try to get the expertises, I get the collection is not associated with any session exception,

Here is my get method:

public List<Expertise> getExpertises() {

    Hibernate.initialize(expertises);

    if (expertises != null) {
        return expertises.stream().distinct().collect(Collectors.toList());
    }
    return null;
}

and when I remove the Hibernate.initialize, I get the org.hibernate.LazyInitializationException, even thought I have able_lazy_load_no_trans">true</property> in my config file.

So my question is what am I doing wrong, and how to properly initialize a lazy collection and retrieve it. Or should I just stick with eager fetching.

UPDATE: Adding @LazyCollection(LazyCollectionOption.TRUE) to the collections did the trick, but is it really lazy? does it really only loads the list when needed?

Ouerghi Yassine
  • 1,646
  • 7
  • 39
  • 66

0 Answers0