Hello,
I have a problem with sessions.
Here is the code I'm trying to run in the Main method
Code:
Session s = HibernateSessionFactory.getSession();
PEnforcementOrder order = null;
try {
order = PEnforcementOrder.getById(53);
} catch (DbObjectNotFoundException donfe) {
donfe.printStackTrace();
}
for(Iterator<PEnforcementDesignation> it = order.getEnforcementDesignations().iterator(); it.hasNext();)
System.out.println(it.next().getDesignation());
s.close();
Here is the code of the getById() method (I'm aware of the session.load() function so this is just example)
Code:
public static PEnforcementOrder getById(long id) throws DbObjectNotFoundException {
Session s = HibernateSessionFactory.getSession();
String query = "from PEnforcementOrder e where enforcementOrderId=:id";
Query q = s.createQuery(query);
q.setLong("id", id);
List<PEnforcementOrder> l = q.list();
s.close();
if(l.isEmpty())
throw new DbObjectNotFoundException(query + " " + id);
return l.iterator().next();
}
I'm getting the error:
Exception in thread "main" org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: si.nkbm.ris.persistance.PEnforcementOrder.enforcementDesignations, no session or session was closed
It's obvious that the session which is opened in the Main method closes in the getById method and because of that the EnforcementOrder object is not usable afterwards to connect to other persistant classes.
How to handle sessions to avoid such type of behaviour. I need those functions to retrieve objects and then to connect to other objects?
Thanks