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 of object to the Gson function called toJson.
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
Here it is my Conversazione class:
@Entity
@Table(name="conversazione")
public class Conversazione {
@Id
@Column(name="id")
@NotNull
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
@Column(name="nome", length = 128)
private String nome;
@Column(name="foto", length = 256, nullable = true)
private String foto;
@OneToMany(mappedBy = "idConversazione")
private List<Partecipante> partecipanti = new ArrayList<>();
@OneToMany(mappedBy = "conversazioneId")
private List<Messaggio> messaggi = new ArrayList<>();
@Temporal(TemporalType.TIMESTAMP)
@Column(name="data_creazione", nullable = false)
private Date dataCreazione;
public Conversazione() {
this.nome = nome;
this.foto = foto;
this.dataCreazione = dataCreazione;
}
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.