0

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
apwnn
  • 87
  • 7
  • I personnaly only use Jackson, i never used Gson beaucose the first one gives me what i want. i deleted my answer because it didn't propose a way of doing with your library. Check if this https://stackoverflow.com/questions/11746499/how-to-solve-the-failed-to-lazily-initialize-a-collection-of-role-hibernate-ex will solve your problem. – Big Zed Jan 16 '21 at 18:33
  • So what does `System.out.println(conversations);` print? Also show your `Conversazione`. What happens if you move `gson.toJson(...)` before `factory.close()`? – pirho Jan 17 '21 at 08:38
  • @pirho the `System.out.println(conversations);` prints me the list of Conversazione objects I was looking for. The problem appears when I do `gson.toJson(conversations);`. I also tried to move `gson.toJson(...)` before `factory.close()` but gives me the same error. – apwnn Jan 18 '21 at 09:04
  • So you can see all `partecipanti`? – pirho Jan 18 '21 at 13:18
  • @pirho no because `partecipanti` is empty. `private List partecipanti = new ArrayList<>();` is there cause is a @OneToMany reletionship – apwnn Jan 18 '21 at 13:34
  • @pirho maybe I solved writing `private transient List partecipanti = new ArrayList<>();` in my Conversazione class. I added `transient` and it seems to work – apwnn Jan 18 '21 at 13:35
  • How about `@OneToMany(fetch = FetchType.EAGER)`? And test it also with a list that has items... – pirho Jan 18 '21 at 13:39
  • @pirho I've tried it before but I didn't work – apwnn Jan 18 '21 at 13:54

0 Answers0