I got a list of objects where a save the result of a query using hibernate. The query works fine and print me out the right result. The problem is when I try to pass this list to toJson() it gives me an error. I have also tried to create a list of Conversazione objects and pass it to the Gson function toJson() and it works fine as it should. So the problem is for sure with hibernate. Here it is my code:
List<Conversazione> conversations;
SessionFactory factory = new Configuration()
.configure("hibernate2.cfg.xml")
.addAnnotatedClass(Conversazione.class)
.buildSessionFactory();
Session session = factory.getCurrentSession();
try {
session.beginTransaction();
//HERE IT IS MY QUERY
conversations = session.createQuery("from Conversazione ").list();
session.getTransaction().commit();
}
finally {
factory.close();
}
//when I print it everything is fine
System.out.println(conversations);
Gson gson = new Gson();
//this is where the problem come from
String json = gson.toJson(conversations);
System.out.println(json);
Here it is the error that it gives me:
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: database.Conversazione.partecipanti, could not initialize proxy - no Session