简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM