In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >
Share
Shulou(Shulou.com)05/31 Report--
This article mainly introduces "how to understand SqlSession technology". In daily operation, I believe many people have doubts about how to understand SqlSession technology. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the doubts about "how to understand SqlSession technology"! Next, please follow the editor to study!
The old rule, first on the case code, we follow this case step by step to get the Mybatis source code.
Public class MybatisApplication {public static final String URL = "jdbc:mysql://localhost:3306/mblog"; public static final String USER = "root"; public static final String PASSWORD = "123456"; public static void main (String [] args) {String resource = "mybatis-config.xml"; InputStream inputStream = null; SqlSession sqlSession = null; try {inputStream = Resources.getResourceAsStream (resource) SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder (). Build (inputStream); sqlSession = sqlSessionFactory.openSession (); UserMapper userMapper = sqlSession.getMapper (UserMapper.class); System.out.println (userMapper.selectById (1));} catch (Exception e) {e.printStackTrace ();} finally {try {inputStream.close () } catch (IOException e) {e.printStackTrace ();} sqlSession.close ();}}
As many friends are urging me to say when the Mybatis source code series will come down, Lao Tian stayed up late to write this article.
Continue to play ~
SqlSession sqlSession = sqlSessionFactory.openSession ()
As analyzed in the previous article, the sqlSessionFactory here is actually DefaultSqlSessionFactory.
So here, let's start with the openSession method in DefaultSqlSessionFactory.
Public class DefaultSqlSessionFactory implements SqlSessionFactory {private final Configuration configuration; public DefaultSqlSessionFactory (Configuration configuration) {this.configuration = configuration;} / / create session, which directly calls another method in this class @ Override public SqlSession openSession () {return openSessionFromDataSource (configuration.getDefaultExecutorType (), null, false);} / / actually calls this method private SqlSession openSessionFromDataSource (ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {Transaction tx = null Try {/ / corresponds to the xml tag, which is already stored in configuration when the configuration file is parsed. Final Environment environment = configuration.getEnvironment (); final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment (environment); tx = transactionFactory.newTransaction (environment.getDataSource (), level, autoCommit); / / create an executor to execute SQL final Executor executor = configuration.newExecutor (tx, execType); / / also explain why SqlSession in our code is DefaultSqlSession return new DefaultSqlSession (configuration, executor, autoCommit);} catch (Exception e) {closeTransaction (tx) / / may have fetched a connection so lets call close () throw ExceptionFactory.wrapException ("Error opening session. Cause: "+ e, e);} finally {ErrorContext.instance (). Reset ();}} private TransactionFactory getTransactionFactoryFromEnvironment (Environment environment) {if (environment = = null | | environment.getTransactionFactory () = = null) {return new ManagedTransactionFactory ();} return environment.getTransactionFactory ();}
The main contents of this method are:
Next, let's break through one by one.
Create a transaction Transaction
The transaction factory type can be configured as either JDBC or MANAGED.
JdbcTransactionFactory produces JdbcTransaction.
ManagedTransactionFactory produces ManagedTransaction.
If JDBC is configured, the commit (), rollback (), and close () methods of the Connection object are used to manage the transaction.
If we configure MANAGED, we will leave the transaction to the container to manage, such as JBOSS,Weblogic. Because we are a local program, if configured as MANAGED, there will be no transactions.
However, if our project is Spring integration Mybatis, there is no need to configure transactions, because we will configure the data source and transaction manager directly in applicationContext.xml, thus overriding the configuration of Mybatis.
Create Actuator Executor
Call the newExecutor method of configuration to create an Executor.
Final Executor executor = configuration.newExecutor (tx, execType); / / public Executor newExecutor (Transaction transaction, ExecutorType executorType) {executorType = executorType = = null? DefaultExecutorType: executorType; executorType = executorType = = null? ExecutorType.SIMPLE: executorType; Executor executor; / / first step if (ExecutorType.BATCH = = executorType) {executor = new BatchExecutor (this, transaction);} else if (ExecutorType.REUSE = = executorType) {executor = new ReuseExecutor (this, transaction);} else {executor = new SimpleExecutor (this, transaction);} / / second step if (cacheEnabled) {executor = new CachingExecutor (executor) } / / step 3 executor = (Executor) interceptorChain.pluginAll (executor); return executor;}
This method is divided into three steps.
Step 1: create an actuator
There are three basic types of Executor:
Public enum ExecutorType {SIMPLE, REUSE, BATCH}
SIMPLE is the default type.
Why let the abstract class BaseExecutor implement the Executor interface, and then let the concrete implementation class inherit the abstract class?
This is the implementation of the template method pattern.
The template method pattern is to define an algorithm skeleton and allow subclasses to provide implementation for one or more steps. The template method is some of the steps to redefine the algorithm without changing the structure of the algorithm.
Abstract methods are implemented in subclasses, each executor implements its own logic, and BaseExecutor is eventually called into a concrete subclass.
Abstract method
Protected abstract int doUpdate (MappedStatement ms, Object parameter) throws SQLException; protected abstract List doFlushStatements (boolean isRollback) throws SQLException; protected abstract List doQuery (MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException; protected abstract Cursor doQueryCursor (MappedStatement ms, Object parameter, RowBounds rowBounds, BoundSql boundSql) throws SQLException
Step 2: cache decoration
The second step in the above code
If (cacheEnabled) {executor = new CachingExecutor (executor);}
If cacheEnabled=true, the Executor is decorated with the decorator design pattern.
Step 3: after the plug-in proxy cache is decorated, it will execute
Executor = (Executor) interceptorChain.pluginAll (executor)
Plug-in logic will be implanted into Executor here.
For example, the Executor that the plug-in needs to be implanted in the paging plug-in
Well, at this point, the creation of the actuator is done.
Create a DefaultSqlSession object
Assign the Configuration object created by the previous parsing configuration file and the created executor Executor to the properties in DefaultSqlSession.
Public DefaultSqlSession (Configuration configuration, Executor executor, boolean autoCommit) {this.configuration = configuration; this.executor = executor; this.dirty = false; this.autoCommit = autoCommit;}
At this point, the SqlSession (DefaultSqlSession) object is created.
At this point, the study on "how to understand SqlSession technology" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.