Getting Started 25 - Session Management
Session is the center of Hibernate, the life cycle of the object, the management of the transaction, the database is accessed, and it is closely related to the session interest. It is like the management of Connection, created, using and reclaiming the Connection, Reduce resource consumption, increase system execution efficiency, effective session management, is also focus on Hibernate applications. Session is created by SessionFactory, and sessionFactory is a "Thread-Safe), you can have multiple execution to access SessionFactory without data sharing, however, SESSION is not designed to be safe, So try to make multiple execution shares a session, and there will be a problem with data sharing. In the first chapter of the Hibernate Reference Manual Quick Start, a Hibernateutil is demonstrated, which uses the ThreadLocal category to create a session management auxiliary class, which is Hibernate's session management a widely applying solution, threadlocal is Thread- A operational instance of the Specific Storage mode, you can learn about Thread-Specific Storage mode in this article: DesignPattern: Thread-Specific Storage Since the Thread-Specific Stroage mode can effectively isolate the data used by the execution, avoid the session Data sharing problem between multi-execute, the HibernateUtil class in the Hibernate reference manual is listed below:
Hibernateutil.java
Import net.sf.hibernate. *;
Import net.sf.hibs. *;
Public class hibernateutil {
Private static log log = logfactory.getlog (HibernateUtil.class);
PRIVATE STATIC FINAL SESSIONFACTORY SESSIONFACTORY;
STATIC {
Try {
// Create the sessionFactory
SESSIONFACTORY = New Configuration (). CONFIGURE (). BuildSessionFactory ();
} catch (throwable ex) {
Log.Error ("Initial SessionFactory Creation Failed.", EX);
Throw New ExceptioninInitializerError (ex);
}
}
PUBLIC Static Final Threadlocal session = new threadlocal ();
Public static session currentsession () throws hibernateException {
Session s = (session) session.get ();
// Open a new session, if this thread HAS NONE YET
IF (s == NULL) {
S = sessionFactory.openSession ();
Session.set (s);
}
Return S;
}
Public static void closesession () THROWS HibernateException {
Session s = (session) session.get ();
session.set (null);
IF (s! = null)
s.close ();
}
}
In the same permeation, SESSION is temporarily stored, but it is not necessary to worry that the database links Connection continues to occupy the problem, and Hibernate will acquire the connection when you really need the database operation (from the connection pool). In a web application, we can use the Filter to perform session management, turn on the session when needed, and close the session after the Request, there is a good example on the Wiki of JavaWorld: http: // Www.javaworld.com.tw/confluence/pages/viewpage.Action?pageId=805
In addition, there is also an introduction to Hibernate Chinese online: http://www.hibernate.org.cn/80.html