Hibernate Session Management on

sponsored links
On the Blog: http://blog.csdn.net/jhxck/
Session management options in the various, ThreadLocal pattern has been widely used. ThreadLocal is a Java thread in a more specific binding mechanism. ThreadLocal access through the data is always associated with the current thread, that is, JVM for each running thread, binding the local instance of the access of private space, which often appear as multi-threaded environment, concurrent access issues a a kind of isolation mechanism. First, we need to know, SessionFactory responsible for creating Session, SessionFactory is a thread-safe, multiple concurrent threads can simultaneously access an instance of SessionFactory and obtain Session. And
Session is not thread-safe, that is, if multiple threads simultaneously using a Session instance data access,
Session data access is the logical result will be chaos. The following is a typical Servlet, we are trying to achieve through a class variable Session session reuse, in order to avoid to be re-created for each operation:
public class TestServlet extends HttpServlet (
private Session session;
public void doGet (HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException (
session = getSession ();
doSomething ();
session.flush ();
)
public void doSomething () (
......// Access operation based on session
)
)
Code looks correct, even when we single test might not happen, but this generation of
Hibernate Developer's Guide Version 1.0
September 2, 2004 So many open source projects. Why not Open your Documents?
Once the compiled code to deploy to the actual operating environment, the incoming inexplicable errors are likely to make us feel not looking for head.
What is wrong?
First of all, Servlet running a multi-threaded, while the application server and not for each thread to create a Servlet
Instance, that is, TestServlet in only one instance of the application server (Tomcat in this is the case in other application servers may have different implementations), and this instance would be invoked as many concurrent threads, doGet method will also be different thread repeatedly calls can imagine, each call to doGet method, the only instance TestServlet
session variables are reset, the thread A running process, the other thread was, if implemented, then the session
Reference will change again after the thread A called session, the session may time before its use
session is no longer the same, obviously, the error also unexpected.
ThreadLocal appearance, making the problem solved.
Our example above, some minor modifications:
public class TestServlet extends HttpServlet (
private ThreadLocal localSession = new ThreadLocal ();
public void doGet (HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException (
localSession.set (getSession ());
doSomething ();
session.flush ();
)
public void doSomething () (
Session session = (Session) localSession.get ();
......// Access operation based on session
)
)
You can see, localSession a ThreadLocal object of type, in the doGet method, we adopted the method to obtain the session set examples preserved in the doSomething method, get way out through the session instance.
This is the ThreadLocal is unique, it will for each thread maintains a private variable space. In fact,
The implementation principle is maintaining a JVM in the Map, the Map's key is that the current thread object, the value is the thread through the method of preservation of the object instance ThreadLocal.set. When the thread calls ThreadLocal.get method,
ThreadLocal object based on a reference to the current thread, remove the Map corresponding object to return.
This, ThreadLocal object through a reference to each thread as a distinction between the different threads of variables to isolate.

Hibernate example of official development manual provides a safeguard through the ThreadLocal Session of the good example:

public class HibernateUtil (
private static SessionFactory sessionFactory;
static (
try (
/ / Create the SessionFactory
sessionFactory = new
Configuration (). Configure (). BuildSessionFactory ();
) Catch (HibernateException ex) (
throw new RuntimeException (
"Configuration problem:" + ex.getMessage (),
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 code, as long as the use of the above tools for the Session instance, we can achieve within the thread
Session sharing, in order to avoid frequent in the thread creation and destruction of Session instance. But note that the end of the thread closed Session.

It is also worth mentioning that the new version of the Hibernate Session when dealing with lazy loading mechanism has been built, only the database operations happen in real time, will be from the database connection pool for database connection, we need not worry too much about Session of sharing will lead to the thread life cycle database connection is continued occupation.

The Web program, we can make use of the new specification introduced Servlet2.3 Filter mechanism, easy life-cycle thread
Session management (on the Filter specific description, please refer to Servlet2.3 specification).
Filter runs through the life cycle of their coverage Servlet (JSP can also be seen as a special Servlet)
And the underlying object. Called before the Servlet Filter implementation, after the end of the call in the Servlet. Therefore,
Session for the Filter in the management process as it becomes ripe for Web. The following is a Filter for Session management through a typical case:
public class PersistenceFilter implements Filter
(
protected static ThreadLocal hibernateHolder = new ThreadLocal ();
public void doFilter (ServletRequest request, ServletResponse
response, FilterChain chain)
throws IOException, ServletException
(
hibernateHolder.set (getSession ());
try
(
......
chain.doFilter (request, response);
......
)
finally
(
Session sess = (Session) hibernateHolder.get ();
if (sess! = null)
(
hibernateHolder.set (null);
try
(
sess.close ();
)
catch (HibernateException ex) (
throw new ServletException (ex);
)
)
)
)
......
Hibernate Developer's Guide Version 1.0
September 2, 2004 So many open source projects. Why not Open your Documents?
)
DoFilter get by on and off Session, and in the period running all objects (Filter chain, the rest of the Filter, and cover the Servlet and other objects) to reuse an instance of this Session, to ensure a
Http Request processing takes a Session, improve overall performance.
In the actual design, Session reuse achieve thread-level general enough in an attempt to achieve through the HttpSession Session user level reuse but may cause other problems. Everything can not be too far, Session reuse the same.

On the Blog: http://blog.csdn.net/jhxck/
  • del.icio.us
  • StumbleUpon
  • Digg
  • TwitThis
  • Mixx
  • Technorati
  • Facebook
  • NewsVine
  • Reddit
  • Google
  • LinkedIn
  • YahooMyWeb

Related Posts of Hibernate Session Management on

  • Software Performance

    1.1 Software Performance In general, the performance is an indicator that the software system or component to its timeliness requirements in line with the level; followed by software performance, are an indicator can be used to measure time. Performa ...

  • JUnit Unit Testing Summary

    Read some of the unit test article, from the article in the interception of a number of information, which could be considered in the learning process, a summary of it! See future! Unit testing code is not used to prove you are right, but in order to ...

  • hibernate (jpa) composite primary key annotation statement Ways

    In the design of the database tables are designed with a composite primary key of the table, that table's record by more than one field joint identification, such as: Table CREATE TABLE TB_HOUR_DATA ( STAT_DATE DATE NOT NULL, PATH_ID NUMBER(20) NOT NULL,

  • jboss ejb3 Message Driven Bean

    Super Medium ejb hate. . . . . . . . . . . . . . . . . . . ================================================ To configure a Message Driven Bean in a different application server parameters are not the same. Currently only passed the test jboss. Message Dri

  • Process migration from tomcat to websphere changes

    Process migration from tomcat to websphere changes Because customers use the web application server software used by different what tomcat5, tomcat6, websphere5.1, websphere6.1, weblogic8, and so on, and the software used inconsistent standards, ibm's

  • myeclipse plugin

    myeclipsePlug-ins? 1.tomcatPlugin(Start tomcat ):http ://www.sysdeo.com/eclipse/tomcatPlugin.html,2.xVersions of eclipse 3 version 2 .1Version doesn't work. 2.Lomboz(Development of jsp program ,jspDynamic prompt, debugging ):http://forge.objectweb.org/pro

  • hibernate generic generic DAO

    package org.lzpeng.dao; import java.io.Serializable; import java.util.List; import org.hibernate.Criteria; import org.hibernate.Query; import org.hibernate.criterion.Criterion; import org.springside.modules.orm.hibernate.Page; /** * * @version 2009-1-10 *

  • Servlet brief introduction

    Servlet brief introduction: Servlet is a small application server Are used to complete the B / S architecture, the client requests the response to treatment Platform independence, performance, able to run thread Servlet API for Servlet provides the s ...

  • Great collection of java interview topics

    1, object-oriented features of what has 1. Abstract: Abstract is that it has overlooked a subject has nothing to do with the current goal of those aspects in order to more fully with the current objectives of the attention-related aspects. Abstract does n

blog comments powered by Disqus
Recent
Recent Entries
Tag Cloud
Random Entries