Chetan Sharma
Chetan Sharma

Reputation: 193

session.clear() is necessary?

I am using Hibernate for my all database related task . I am using a HIbernateUTIl class to maintain the connections and doing something like this

Session session = null;
SessionFactory sessionfactory = HibernateUtil.getSessionFactory();
session = sessionfactory.openSession();

at the end of the code in the finally block i do

session.close();

and after that my function gets over , inside the function i am firing some queries and getting the result in arraylist.

my question is that : is the primary level cache is cleared as soon as i am closing the session or i have to forcibly clear that with

session.clear()

and if the primary cache is not cleared will it hold the refernces to my object , which will make them unreachable for garbage collection and ultimately a memory loss .. please help

Upvotes: 3

Views: 7502

Answers (1)

JB Nizet
JB Nizet

Reputation: 691725

No, calling session.clear() is not necessary. Closing the session also clears it.

Clearing the session is useful when you have long-running sessions, or when doing batch updates, which keep a large amount of entities in memory, to avoid out or memory errors. But if you only keep a session open for the duration of a typical transaction, clear isn't necessary.

Upvotes: 2

Related Questions