In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "MyBatis startup and the role of various classes", the content of the article is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in depth, together to study and learn "MyBatis startup and the role of various classes" bar!
Preface
MyBatis as one of the most commonly used persistence layer framework, analyze its source code, we can better use it in the process of use. This series is based on mybatis-3.4.6 analysis. The initialization of MyBatis is to parse the main configuration file, mapping configuration file, and annotation information. It is then saved in org.apache.ibatis.session.Configuration for later calls to perform data requests. There is a lot of configuration information in Configuration, and each related configuration will be analyzed in detail later.
Start public static void main (String [] args) throws IOException {/ / get the configuration file Reader reader = Resources.getResourceAsReader ("mybatis-config.xml"); / / build the sqlSession factory SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder (). Build (reader) through SqlSessionFactoryBuilder; / / get sqlSession instance SqlSession sqlSession = sqlSessionFactory.openSession (); reader.close (); sqlSession.close () } analyze SqlSessionFactoryBuilder classes
SqlSessionFactoryBuilder's build () is the initialization entry for Mybatis startup and loads the configuration file using builder mode. By looking at this class and using method overloading, there are nine methods:
The source code for the final implementation of method overloading is as follows:
Public SqlSessionFactory build (Reader reader, String environment, Properties properties) {try {/ / instantiate XMLConfigBuilder to read configuration file information XMLConfigBuilder parser = new XMLConfigBuilder (reader, environment, properties); / / parse configuration information and save it to Configuration return build (parser.parse ());} catch (Exception e) {throw ExceptionFactory.wrapException ("Error building SqlSession.", e) } finally {ErrorContext.instance (). Reset (); try {reader.close ();} catch (IOException e) {/ / Intentionally ignore. Prefer previous error. }}}
Environment is the specified loading environment, and the default value is null.
Properties is a property profile, and the default value is null. At the same time, the read configuration file can be read by both character stream and byte stream.
Public SqlSessionFactory build (InputStream inputStream, String environment, Properties properties) {try {XMLConfigBuilder parser = new XMLConfigBuilder (inputStream, environment, properties); return build (parser.parse ());} catch (Exception e) {throw ExceptionFactory.wrapException ("Error building SqlSession.", e);} finally {ErrorContext.instance (). Reset (); try {inputStream.close () } catch (IOException e) {/ / Intentionally ignore. Prefer previous error. Instantiate the XMLConfigBuilder class
The instantiation process of XMLConfigBuilder is analyzed by XMLConfigBuilder parser = new XMLConfigBuilder (reader, environment, properties) in SqlSessionFactoryBuilder. There are four variables in this class:
Private boolean parsed; private final XPathParser parser; private String environment; private final ReflectorFactory localReflectorFactory = new DefaultReflectorFactory ()
Whether the parsed is parsed or not can be parsed once. Used for flag configuration files are parsed only once, true is parsed.
Parser for parser parsing configuration
Environment loading environment, that is, environment in SqlSessionFactoryBuilder
LocalReflectorFactory is used to create and cache Reflector objects, one Reflector for each class. Because a large number of reflection operations are involved in parameter processing, result mapping and so on. The DefaultReflectorFactory implementation class is relatively simple and will not be explained here.
XMLConfigBuilder builds the function implementation:
Public XMLConfigBuilder (Reader reader, String environment, Properties props) {this (new XPathParser (reader, true, props, new XMLMapperEntityResolver ()), environment, props);} instantiate XPathParser object
First instantiate the XPathParser object, which defines five variables:
Private final Document document; private boolean validation; private EntityResolver entityResolver; private Properties variables; private XPath xpath
Document saves document objects
Whether to validate the document during validation xml parsing
EntityResolver loads dtd files
Values defined by the variables profile
Xpath Xpath object for manipulating XML file nodes
The XPathParser object constructors are:
Two things are handled in the function:
Public XPathParser (Reader reader, boolean validation, Properties variables, EntityResolver entityResolver) {commonConstructor (validation, variables, entityResolver); this.document = createDocument (new InputSource (reader);}
Initialize assignments, and create XPath objects for operations on XML file nodes.
Private void commonConstructor (boolean validation, Properties variables, EntityResolver entityResolver) {this.validation = validation; this.entityResolver = entityResolver; this.variables = variables; / / create a Xpath object for manipulating XML file nodes XPathFactory factory = XPathFactory.newInstance (); this.xpath = factory.newXPath ();}
Create a Document object and assign it to the document variable. This belongs to the operation created by Document. It will not be described in detail. If you do not understand, click here to view the API.
Private Document createDocument (InputSource inputSource) {/ / important: this must only be called AFTER common constructor try {/ / instantiate the DocumentBuilderFactory object to create the DocumentBuilder object DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance (); / / whether to verify the document factory.setValidating (validation); / / set the configuration factory.setNamespaceAware (false) of DocumentBuilderFactory; factory.setIgnoringComments (true) Factory.setIgnoringElementContentWhitespace (false); factory.setCoalescing (false); factory.setExpandEntityReferences (true); / / create DocumentBuilder DocumentBuilder builder = factory.newDocumentBuilder (); builder.setEntityResolver (entityResolver); builder.setErrorHandler (new ErrorHandler () {@ Override public void error (SAXParseException exception) throws SAXException {throw exception) } @ Override public void fatalError (SAXParseException exception) throws SAXException {throw exception;} @ Override public void warning (SAXParseException exception) throws SAXException {}}); / / load the file return builder.parse (inputSource) } catch (Exception e) {throw new BuilderException ("Error creating document instance. Cause: "+ e, e);}} XMLConfigBuilder constructor assignment private XMLConfigBuilder (XPathParser parser, String environment, Properties props) {super (new Configuration ()); ErrorContext.instance () .resource (" SQL Mapper Configuration "); this.configuration.setVariables (props); this.parsed = false; this.environment = environment; this.parser = parser;}
Initializes the value of the parent class BaseBuilder.
Assign an external value to the object.
Assign the instantiated XPathParser to parser.
Finally, the XMLConfigBuilder object is returned.
Parsing XMLConfigBuilder object
Parse the configuration information through XMLConfigBuilder.parse () and save it to Configuration. The detailed explanation of the analysis is analyzed in the following article.
Public Configuration parse () {/ / whether the configuration file if (parsed) {throw new BuilderException ("Each XMLConfigBuilder can only be used once.");} / / flag has been parsed, defined as true parsed = true; / / parsing the information in the configuration node parseConfiguration (parser.evalNode ("/ configuration")); return configuration;} create SqlSessionFactory
DefaultSqlSessionFactory implements the SqlSessionFactory interface. With the Configuration parsed above, call SqlSessionFactoryBuilder.build (Configuration config) to create a DefaultSqlSessionFactory.
Public SqlSessionFactory build (Configuration config) {return new DefaultSqlSessionFactory (config);}
The process of instantiating DefaultSqlSessionFactory is to pass Configuration to the DefaultSqlSessionFactory member variable configuration.
Public DefaultSqlSessionFactory (Configuration configuration) {this.configuration = configuration;} create SqlSession
Create the SqlSession by calling SqlSessionFactory.openSession ().
Public interface SqlSessionFactory {/ / create SqlSession openSession (); SqlSession openSession (boolean autoCommit); SqlSession openSession (Connection connection); SqlSession openSession (TransactionIsolationLevel level); SqlSession openSession (ExecutorType execType); SqlSession openSession (ExecutorType execType, boolean autoCommit); SqlSession openSession (ExecutorType execType, TransactionIsolationLevel level); SqlSession openSession (ExecutorType execType, Connection connection); Configuration getConfiguration ();}
Whether autoCommit automatically commits transactions
Level transaction isolation level (a total of 5 levels), you can view the relevant source code
Connection connection
Types of execType executors: SIMPLE (no special processing), REUSE (reuse preprocessing statements), BATCH (batch execution)
Because the above DefaultSqlSessionFactory implements the SqlSessionFactory interface, go to DefaultSqlSessionFactory to see openSession ().
Public SqlSession openSession () {return openSessionFromDataSource (configuration.getDefaultExecutorType (), null, false);}
The final implementation code of the openSession () method is as follows:
Private SqlSession openSessionFromDataSource (ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {Transaction tx = null; try {/ / get the loading environment final Environment environment = configuration.getEnvironment () in configuration; / / get transaction factory final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment (environment); / / create a transaction tx = transactionFactory.newTransaction (environment.getDataSource (), level, autoCommit) / / generate a processor, and the transaction is stored in the processor BaseExecutor final Executor executor = configuration.newExecutor (tx, execType); / / instantiate a DefaultSqlSession,DefaultSqlSession to implement the SqlSession interface return new DefaultSqlSession (configuration, executor, autoCommit);} catch (Exception e) {/ / turn off transaction closeTransaction (tx) in case of exception / / may have fetched a connection so lets call close () throw ExceptionFactory.wrapException ("Error opening session. Cause: "+ e, e);} finally {/ / recharge error instance context ErrorContext.instance (). Reset ();}}
Generation processor Configuration.newExecutor (Transaction transaction, ExecutorType executorType):
Public Executor newExecutor (Transaction transaction, ExecutorType executorType) {/ / defaults to ExecutorType.SIMPLE executorType = executorType = = null? DefaultExecutorType: executorType; executorType = executorType = = null? ExecutorType.SIMPLE: executorType; Executor executor; 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);} if (cacheEnabled) {executor = new CachingExecutor (executor) } executor = (Executor) interceptorChain.pluginAll (executor); return executor;}
Take ExecutorType.SIMPLE as an example, BatchExecutor and ReuseExecutor are the same:
Thank you for your reading, the above is the content of "MyBatis startup and the role of various classes". After the study of this article, I believe you have a deeper understanding of MyBatis startup and the role of various classes, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
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.