1

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.

skaffman
  • 398,947
  • 96
  • 818
  • 769
Ouerghi Yassine
  • 1,835
  • 7
  • 43
  • 72
  • 1
    This is a very common problem. [I wrote a kind of Q&A on Hibernate that you might find helpful](http://stackoverflow.com/a/24257450/2357233). Skip down to the section on `Determining your fetchType` about halfway down the answer for how you can solve your `LazyInitializationException` – JamesENL Mar 23 '15 at 03:54

1 Answers1

1

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.

Ueli Hofstetter
  • 2,409
  • 4
  • 29
  • 52