Search code examples
javahibernatesessionormcriteria

Do you need to commit/close a session after doing a Criteria query in Hibernate?


I have a code that looks like this:

Session session = MySessionFactory.createSession();
session.beginTransaction();
Criteria cq = session.createCriteria(clazz);
// Do stuff.
List list = cq.list();
session.getTransaction().commit();
session.close();

Do I actually need the beginTransaction(), commit(), and close()?

I heard in JPA, CriteriaQuery (as opposed to Criteria) does not require active transaction management.


Solution

  • Yes, you need the session management. However, you can do multiple operations/queries within a single transaction/session. I would recommend starting with a single transaction per request (if you are creating a web server), job, etc. and increase the granularity of the transactions as needed.

    If you want to avoid Spring then this can still be easily done with aspects however you will quickly end up repeating a lot of the work spring has done.