The session object is designed to be a lightweight, disposable object
that you can open and dispose on demand..
You should not try to reuse it on your own (like singleton)
The real problem is thread safety:
while the SessionFactory object is thread safe, the session object is not
and will cause havoc when pointed from several threads.
If you don't want to open a new session every time you can use the current session option which allows you to bind a session to a specific context (like a thread) within the session factory and then retrieve it each time..
Hibernate session management
-
14-04-2022 - |
Domanda
I'm using hibernate and have some trouble in how to use session, which is best method :
use one session and open it in singleton
public static CommonServiceImpl getInstance() { if (session == null || !session.isOpen() ) { session = sessionFactory.openSession(); } //session.clear(); return instance; }
Use
SessionFactory
each time when i wanna use the session withsessionFactory.getCurrentSession()
?
Soluzione
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow