How/When to Close Hibernate Session?

Asked

Viewed 576 times

5

I have an error after closing Hibernate Session

public String listarTodosClientes() {
    session.getTransaction().begin();
    List<Cliente> lista = session.createCriteria(Cliente.class).list();
    session.close();
    return lista.toString();
}

After Session.close() the toString() method generates an Exception. But if I remove Session.close(). The code works. And now I can leave the sitting open?

p.s: return number string was just an example. could be returning some item from the list.

1 answer

3

RESOLVED.

Solution!

public String listarTodosClientes() {
    session.getTransaction().begin();
    List<Cliente> lista = session.createCriteria(Cliente.class).list();
    String retorno = lista.toString();
    session.close();
    return retorno;
}
  • Are you sure to return the toString() is the best solution to get a customer list?

  • I’m at this very moment with an error like yours, but in a different context, you in your "client" class have no implemented "Set" that is created because of some link that this table has with another?

  • Gustavo this was a summary method, because he did not want to send the whole code. I actually return a Json. And I have another problem that I will post in another question. Gson can not convert the list by calling the method, new Gson(). toJson(list) in this method occurs an Exception.

  • jsantos has yes, already solved it in another link posted the solution. http://answall.com/questions/40334/erro-ao-construir-json-de-um-objeto-recuperado-pelo-hibernate?noredirect=1#comment79301_40334

Browser other questions tagged

You are not signed in. Login or sign up in order to post.