Close session in hibernate when returning an ArrayList

1

I have a problem wanting to close a session in hibernate. I enclose the code that works for me

public ArrayList<Empresa> getEmpresas() {

    Session session = null;

    SessionFactory sesion = HibernateUtil.getSessionFactory();

    session = sesion.openSession();

    Transaction tx = session.beginTransaction();

    Query q = session.createQuery("from Empresa where estado_id=1");

    List<Empresa> lista = q.list();

    return (ArrayList) lista;

}

all right up there, the problem is that the session is staying open and after a few listings I drop and it says too_many_connection because it opens, opens and opens and never closes. Now, if I put session.close(); it throws me a hibernate error, attached Error:

  

message org.hibernate.LazyInitializationException: could not   initialize proxy - no Session.

If you could give me some guidance, I would be very grateful.

PS: I'm working with MySQL and Hibernate

    
asked by Marcelo Nicolas 21.06.2018 в 07:15
source

1 answer

0

In my class Hibernate exercises, we simply add the following code to the end of the method (before the return).

    tx.commit();

Although for those functions in which you want to obtain data, I recommend you use the following structure.

public static Vector <Peregrino> listaPeregrinos (Session sesion) {
        Vector <Peregrino> vPeregrinos = new Vector <Peregrino> ();
        String orden = "from Peregrino order by dni";
        Query consulta = sesion.createQuery(orden);
        Iterator<Peregrino> it = consulta.iterate();
        while (it.hasNext()) {
            vPeregrinos.add(it.next());
        }

        return vPeregrinos;
    }
    
answered by 21.06.2018 в 10:11