Sqlsessionfactorybuilder, Sqlsessionfactory, sqlsession scope (scope) and life cycle

Source: Internet
Author: User
Tags finally block

It can be said that each mybatis is centered on a sqlsessionfactory instance. Sqlsessionfactory instances can be built by Sqlsessionfactorybuilder. One is that the sqlsessionfactory can be built in the form of an XML configuration file, and the second is built through the Java API. However, there is a configuration through which all the configurations are implemented through the config instance.

This article is intended to implement the scope and life cycle guidance recommendations MyBatis3.4.1 User Guide by coding. Why do you know the scope and life cycle? Using Sqlsessionfactorybuilder, Sqlsessionfactory, and sqlsession correctly within the scope will allow us to avoid the problems of concurrency in a multithreaded environment. Of course, if you use the dependency (DI) injection Framework (Spring), you don't have to worry about scope issues in your code, because the dependency injection framework will do almost everything for us.

Let's start by looking at User Guide's guidance on the Sqlsessionfactorybuilder scope and life cycle.

Sqlsessionfactorybuilder

This class can be instantiated, used, and discarded, and once the sqlsessionfactory is created, it is no longer needed. Therefore, the optimal range of Sqlsessionfactorybuilder instances is the method scope (that is, local method variables). You can reuse Sqlsessionfactorybuilder to create multiple sqlsessionfactory instances, but it's best not to keep them alive to ensure that all XML parsing resources are open to more important things.

Sqlsessionfactory

Once created, sqlsessionfactory should exist for the duration of the application and there is no reason to clean it up or rebuild it. The best practice for using sqlsessionfactory is not to repeatedly create multiple times during an app run, and rebuilding sqlsessionfactory multiple times is considered a "bad taste" of code. The optimum range of sqlsessionfactory is therefore the application range. There are many ways to do this, and the simplest is to use singleton mode or static singleton mode.

Sqlsession

Each thread should have its own sqlsession instance. The instance of sqlsession is not thread-safe and therefore cannot be shared, so its best scope is the request or method scope. You must never put a reference to a sqlsession instance in a static domain of a class, or even an instance variable of a class. It is also never possible to place references to sqlsession instances in any type of management scope, such as HttpSession in the Serlvet schema. If you are using a WEB framework now, consider sqlsession in a similar scope to the HTTP request object. In other words, each time you receive an HTTP request, you can open a sqlsession, return a response, and close it. This close operation is important, and you should put the shutdown action in the finally block to ensure that the shutdown is performed every time.

You can see from the User Guide that the scope of the official scopes for Sqlsessionfactorybuilder, sqlsessionfactory, and sqlsession are: Method scope, application scope, request, or method scope, respectively. It is easy for beginners to ignore the scope range of the sqlsessionfactory and place them and Sqlsessionfactorybuilder and sqlsession within the method scope. This does not, in itself, lead to Procedural code errors (which can only cause concurrency problems if the sqlsession is placed in the application scope), but this is considered "bad smell". When I first wrote "MyBatis3," I did not read the user guide so much that the code smelled a "bad smell". example, the code is as follows:

650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Margin:0px;padding:0px;border:none; "/>

1 public class Sessionfactory {2 public static sqlsession Getsqlsession (String Resource) throws Ioexception{3 InputStream InputStream = resources.getresourceasstream (Resource); 4 sqlsessionfactory sqlsessionfactory = new SqlS         Essionfactorybuilder (). Build (InputStream), 5 sqlsession sqlsession = Sqlsessionfactory.opensession (); 6 7 Return sqlsession;8}9}

650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Margin:0px;padding:0px;border:none; "/>

The 4th line of code smells like a "bad smell" because it does not work in the whole range of applications but in the method range.

And what is the better code? We should use Singleton mode for Sqlsessionfactory, as mentioned above. The refactoring code is as follows:

650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Margin:0px;padding:0px;border:none; "/>

 1 package day_8_mybatis.util; 2  3 import java.io.inputstream; 4   5 import org.apache.ibatis.session.SqlSessionFactory; 6 import  org.apache.ibatis.session.sqlsessionfactorybuilder; 7  8 /** 9  * @ author turbo10  *11  * 2016 October 26 12  */13 public class  SessionFactory2 {14     private static SqlSessionFactory  sqlsessionfactory;15     16     public static  Synchronized sqlsessionfactory getinstance (Inputstream inputstream) {17          if  (null == sqlsessionfactory) {18              sqlSessionFactory = new  Sqlsessionfactorybuilder (). Build (InputStream);19         }20         21          return sqlSessionFactory;22      }23 }

650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Margin:0px;padding:0px;border:none; "/>

The client creates sqlsession code as follows:

650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Margin:0px;padding:0px;border:none; "/>

 1 package day_8_mybatis; 2  3 import java.io.ioexception; 4  import java.io.InputStream; 5  6 import org.apache.ibatis.io.Resources;  7 import org.apache.ibatis.session.sqlsession; 8  9 import day_8_ mybatis.util.sessionfactory2;10 11 /**12  *  Client 13  * 14  *   @author  turbo15  *16  * 2016 October 26 17  */18 public  class main {19 20     /**21      *  @param  args22      *  @throws  IOException23       */24     public static void main (String[] args)  throws exception {25         string resource  =  "Day_8_mybatis/mybaTis-config.xml "; //  get MyBatis Profile path 26          Inputstream inputstream = resources.getresourceasstream (Resource);27          sqlsession sqlsession = sessionfactory2.getinstance (InputStream). Opensession (); 28 29     }30 31 }

650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Margin:0px;padding:0px;border:none; "/>

Does this code conform to the standard and looks more comfortable and much more beautiful?


Sqlsessionfactorybuilder, Sqlsessionfactory, sqlsession scope (scope) and life cycle

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.