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.