The difference between Hibernate's sessionfactory getcurrentsession and Opensession ()

Source: Internet
Author: User

1 The session created by Getcurrentsession is bound to the current thread, and Opensession does not.

2 the thread created by Getcurrentsession automatically shuts down after a transaction is rolled back or the thing commits, and opensession must be closed manually

Here the Getcurrentsession local transaction (local transaction: JDBC) is set in the configuration file as follows

* If you are using a local transaction (JDBC Transaction)
<property name= "Hibernate.current_session_context_class" >thread</property>
* If you are using a global transaction (JTA Transaction)
<property name= "Hibernate.current_session_context_class" >jta</property>

Getcurrentsession () using the current session
Opensession () re-establish a new session

In one application, if the DAO layer uses spring's hibernate template to control the session's lifecycle through Spring, getcurrentsession () is preferred.

Most applications that use hibernate require some form of "context-sensitive" session, and a particular session is always valid throughout a specific context. However, it is often difficult for different types of applications to make the next definition of this "context"; different contexts define different scopes for the concept of "current". Prior to version 3.0, programs using hibernate either adopted a self-written threadlocal-based context session, either using an auxiliary class such as Hibernateutil, or using a third-party framework (such as spring or Pico). They provide a context-sensitive session based on proxy or interceptor (interception).

Starting with version 3.0.1, Hibernate adds the Sessionfactory.getcurrentsession () method. At first, it assumes that the JTA transaction is used, and the JTA transaction defines the scope and context of the current session (scope and contexts). The Hibernate development team strongly believes that because there are several independent JTA TransactionManager that are stable to use, whether or not deployed in a Java EE container, most (if not all) applications should have JTA transaction management. Based on this, the context-sensitive session of the JTA can be used to meet all your needs.

Better yet, from 3.1 onwards, the background implementation of sessionfactory.getcurrentsession () is pluggable. Therefore, we introduced the new extension Interface (Org.hibernate.context.CurrentSessionContext) and the new configuration parameters (Hibernate.current_session_context_class), To plug in the definition of what is the scope and context (scope and context) of the "current session".

See the Javadoc of the Org.hibernate.context.CurrentSessionContext interface, where there is a detailed discussion of its contract. It defines a single method, Currentsession (), which is used by the specific implementation to track the current context session. Hibernate has built-in two implementations of this interface.

Org.hibernate.context.JTASessionContext-The current session is tracked and defined according to JTA. This is exactly the same as the previous method of supporting JTA only. Please refer to Javadoc for details.

Org.hibernate.context.ThreadLocalSessionContext-The current session is tracked and defined through the currently executing threads. See also Javadoc for details.

Both implementations provide a programming model for "one session per database transaction", also called a session per request. The start and end of Hibernate session is controlled by the existence of database transactions. If you are using your own code to manage transactions (for example, in pure j2se, or JTA/USERTRANSACTION/BMT), it is recommended that you use the Hibernate Transaction API to hide the underlying transaction implementation from your code. If you are executing in an EJB container that supports CMT, the transaction boundary is defined declaratively, and you do not need to do any transaction or session management operations in your code. See the 11th Transaction and Concurrency section for more content and sample code.

The Hibernate.current_session_context_class configuration parameter defines which Org.hibernate.context.CurrentSessionContext implementation should be used. Note that, in order to be backwards compatible, if this parameter is not configured, but there is a org.hibernate.transaction.TransactionManagerLookup configuration, Hibernate will use Org.hibernate.context.JTASessionContext. Generally, the value of this parameter indicates the full name of the implementation class to be used, but the two built-in implementations can use shorthand, "JTA" and "thread".

1. What is the difference between getcurrentsession () and opensession ()?

The session created by the

* with getcurrentsession () is bound to the current thread, with opensession ()  
The session created will not  
* Sessions created with Getcurrentsession () are automatically closed on commit or rollback, with opensession ()   the session created by
must be manually closed  
2. Use Getcurrentsession () to include the following configuration in the Hibernate.cfg.xml file:  
* If you are using a local transaction (JDBC transaction)  
<property name= " Hibernate.current_session_context_class ">THREAD</PROPERTY>&NBSP;
* If you are using a global transaction (JTA Transaction)  
< Property Name= "Hibernate.current_session_context_class" >JTA</PROPERTY>

Facilitates threadlocal mode management session
As early as the launch of Java1.2, a new support was introduced in the Java platform: java.lang.ThreadLocal, which gives us a multi-threaded program
Provides a new option. What is threadlocal? In fact, Threadlocal is not a local implementation version of a thread,
It is thread local variable (thread locals). Perhaps it would be more appropriate to name it Threadlocalvar. Thread local variables (ThreadLocal)
In fact, the function is very simple, is to use a variable for each thread to provide a copy of the variable value, is each thread can independently change their own copy,
And does not conflict with other threads ' replicas. From a thread's point of view, it's as if every thread has exactly one of those variables.
How does threadlocal maintain a copy of a variable for each thread? In fact, the idea of implementation is very simple, there is a map in the Threadlocal class,
A copy of the variable used to store each thread. For example, the following examples are implemented (for simplicity, no collection is considered for generics):
public class Hibernateutil {

public static final ThreadLocal session =new ThreadLocal ();

Public static final sessionfactory sessionfactory; 
   static { 
       try { 
        sessionfactory = new Configuration (). Configure (). Buildsessionfactory ();  
     } catch (Throwable ex) { 
            throw new Exceptionininitializererror (ex);  
      }     
}

     public static Session currentsession () throws hibernateexception { 
  & nbsp;     Session s = session.get ();  
        if (s = = NULL) { 
          s = sessionfactory.opensession (); 
          Session.set (s);  
           } 
         return s; 
      }

public static void CloseSession () throws Hibernateexception {
Session s = session.get ();
if (s! = null) {
S.close ();
}
Session.set (NULL);
}
}

What are the differences and associations between opensession () and getcurrentsession ()?

When the sessionfactory is started, Hibernate will create the corresponding Currentsessioncontext according to the configuration, and when the Getcurrentsession () is called, the actual method to be executed is Currentsessioncontext.currentsession (). When Currentsession () executes, currentsession calls Sessionfactory opensession if the current Session is empty. So Getcurrentsession () is a better way to get a Session for Java EE.

This article from Csdn Blog, reproduced please indicate the source: http://blog.csdn.net/loveyout/archive/2009/05/17/4193894.aspx

The difference between getcurrentsession and Opensession () of sessionfactory in Hibernate

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.