Can be used directly in every project
1 Package Com.yh.mb.dao;2 3 import Java.io.Reader;4 5 import org.apache.ibatis.io.Resources;6 import org.apache.ibatis.session.SqlSession;7 import org.apache.ibatis.session.SqlSessionFactory;8 import Org.apache.ibatis.session.SqlSessionFactoryBuilder;9 /**Ten * MyBatis Tool class for connecting to the database One * @author Administrator A * - */ - Public classMybatisutil { the PrivateMybatisutil () { - } - Private StaticFinal String RESOURCE ="Mybatis-config.xml"; - Private StaticSqlsessionfactory sqlsessionfactory =NULL; + Private StaticThreadlocal<sqlsession> ThreadLocal =NewThreadlocal<sqlsession>(); - Static { +Reader reader =NULL; A Try { atReader =Resources.getresourceasreader (RESOURCE); -Sqlsessionfactorybuilder Builder =NewSqlsessionfactorybuilder (); -Sqlsessionfactory =Builder.build (reader); -}Catch(Exception E1) { - e1.printstacktrace (); - Throw NewExceptionininitializererror ("Initialize the MyBatis error, please???? configuration file or database"); in - } to } + Public Staticsqlsessionfactory getsqlsessionfactory () { - returnsqlsessionfactory; the } * Public Staticsqlsession getsession () { $ //The Get () method of the Sessiontl returns its corresponding thread intrinsic variable according to the current thread??Panax Notoginseng //that is, we need the session, multi-threaded case of the shared database link is not safe?? - //threadlocal guarantee that each thread has its own session?? thesqlsession session = ThreadLocal.Get(); + //if session is null, open the???? The new session A if(Session = =NULL){ theSession = (Sqlsessionfactory! =NULL)? Sqlsessionfactory.opensession ():NULL; +ThreadLocal.Set(session);//5 - } $ returnsession; $ } - Public Static voidclosesession () { -sqlsession session = (sqlsession) threadLocal.Get();//2 theThreadLocal.Set(NULL); - if(Session! =NULL){Wuyi session.close (); the } - } Wu}
Mybatisutil.java. tool classes, connecting database libraries