As explained in this forum post, 1 and 2 are related. If you set hibernate.current_session_context_class
to thread and then implement something like a servlet filter that opens the session - then you can access that session anywhere else by using the SessionFactory.getCurrentSession()
.
SessionFactory.openSession()
always opens a new session that you have to close once you are done with the operations. SessionFactory.getCurrentSession()
returns a session bound to a context - you don't need to close this.
If you are using Spring or EJBs to manage transactions you can configure them to open / close sessions along with the transactions.
You should never use one session per web app
- session is not a thread safe object - cannot be shared by multiple threads. You should always use "one session per request" or "one session per transaction"
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…