0

I use hibernate to manage my database/javaWebApplication interaction, with new requirements i had to have scrollable results and map my own query results, i made this generic class in java to return scrollableResults

   public ScrollableResults executeCursorQuery(final String
    queryString, final Object... params) throws PersistenceException 
    {

    Session session =  SessionFactoryUtil.getSessionFactory().openSession();

    SQLQuery sqlQuery = session.createSQLQuery(queryString);

    int position = 0;
    for (Object param: params) {
        sqlQuery.setParameter(position, param);
        position++;
    }
    ScrollableResults results = sqlQuery.scroll();

    return results;
}

i iterate over the result and map my info perfectly and after i'm done i do

    SessionFactoryUtil.getSessionFactory().getCurrentSession().close();

it works fairly good but after a few calls to this method it crashes the app, i imagine it is because of the sessions being open every time because i also use c3p0 to handle connection pool. I really don't know i'm on a loop here if anyone spots the error or knows what i'm doing wrong and can point me in the right directions it will be greatly appreciated.

fr3d0
  • 225
  • 1
  • 12
  • Which database are using? – Shankar Jun 27 '16 at 18:57
  • Note that there is a subtle difference between getSession() and openSession() method. If you use openSession() then close the sesssion object by calling session.close(). http://stackoverflow.com/questions/8046662/hibernate-opensession-vs-getcurrentsession – Shankar Jun 27 '16 at 19:03
  • yes but i need the session open to be able to iterate over the result of the query and i close it after im done, but it doesn't seem to be working i posted the line of code i use to close it and it should work but doesn't. – fr3d0 Jun 27 '16 at 19:31

1 Answers1

0

Close the session like this. SessionFactory.openSession() always opens a new session. You have to close it like this.

session.close();

SessionFactoryUtil.getSessionFactory().getCurrentSession().close(); will work only if you have set the property hibernate.current_session_context_class=thread. More details here - Hibernate openSession() vs getCurrentSession()

Community
  • 1
  • 1
Shankar
  • 2,625
  • 3
  • 25
  • 49