Ouerghi Yassine
Ouerghi Yassine

Reputation: 1887

Hibernate OneToMany Lazy Fetching

I'm trying to do a lazying fetching with hibernate, but i always get a LazyInitializationException, i understand this happens because the Hibernate session is closed, and i tend to close the session very next moment i'm done selecting or inserting data. Here is my code: i have a CV class that has many Certificates:

public class Cv implements java.io.Serializable {
    ...
    @OneToMany(mappedBy = "cv",fetch = FetchType.LAZY)
    private Set<Certificate> certificates = new HashSet<>(0);
    ...
    public static List<Cv> getAllCvs() {
        Session session = HibernateUtil.getSessionFactory().openSession();
        try {
            List<Cv> list;

            list = session.createCriteria(Cv.class).addOrder(Order.asc("id")).list();

            if (session.isOpen()) {
                session.close();
            }

            return list;
        } catch (Exception e) {
            if (session.isOpen()) {
                session.close();
            }
            return null;
        }
    }
}



public class Certificate implements java.io.Serializable {
    ...
    @ManyToOne(fetch = FetchType.EAGER)
    private Cv cv;
    ...
}

I have read that i could use Hibernate.initialize but i did not know where to put it.

Upvotes: 1

Views: 3778

Answers (1)

Ueli Hofstetter
Ueli Hofstetter

Reputation: 2524

Update: This is also answered in a post mentioned in the comments (by james)

I assume you get the error when you try to access the certificates. So before you close the session, try something like

try {
        List<Cv> list;

        list = session.createCriteria(Cv.class).addOrder(Order.asc("id")).list();
        for(CV cv: list) {
           Hibernate.initialize(cv.getCertificates());
        } 

        if (session.isOpen()) {
            session.close();
        }

        return list;
    } catch (Exception e) {
        if (session.isOpen()) {
            session.close();
        }
        return null;
    }

which should initialize the certificates so that you can access them even after the session is closed.

However: Keep in mind that explicitly managing sessions and transactions is probably not the best approach in the first place.

Upvotes: 1

Related Questions