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--
Mybatis source code how to write, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain in detail for you, people with this need can come to learn, I hope you can gain something.
The official demo code for mybatisation is as follows
Import org.apache.ibatis.mapping.Environment;import org.apache.ibatis.session.Configuration;import org.apache.ibatis.session.SqlSession;import org.apache.ibatis.session.SqlSessionFactory;import org.apache.ibatis.session.SqlSessionFactoryBuilder;import org.apache.ibatis.transaction.TransactionFactory;import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;import javax.sql.DataSource;public class Mybatis {public static void main (String [] args) {/ * configure data source * / DataSource dataSource=null / * configuration transaction * / TransactionFactory transactionFactory = new JdbcTransactionFactory (); / * data source and transaction combination configuration class * / Environment environment = new Environment ("development", transactionFactory, dataSource); / * configuration class constructor * / Configuration configuration = new Configuration (environment); / * SqlSession factory class * / SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder (). Build (configuration); SqlSession sqlSession = sqlSessionFactory.openSession () SqlSession.update (");}}
DataSource data source
TransactionFactory transaction factory interface, the source code is as follows, the main function is to construct the configuration information of the transaction.
/ * Copyright 2009-2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "ASIS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * / package org.apache.ibatis.transaction;import java.sql.Connection;import java.util.Properties;import javax.sql.DataSource;import org.apache.ibatis.session.TransactionIsolationLevel;/** * Creates {@ link Transaction} instances. * * @ author Clinton Begin * / public interface TransactionFactory {/ * Sets transaction factory custom properties. * @ param props * / void setProperties (Properties props); / * * Creates a {@ link Transaction} out of an existing connection. * @ param conn Existing database connection * @ return Transaction * @ since 3.1.0 * / Transaction newTransaction (Connection conn); / * * Creates a {@ link Transaction} out of a datasource. * @ param dataSource DataSource to take the connection from * @ param level Desired isolation level * @ param autoCommit Desired autocommit * @ return Transaction * @ since 3.1.0 * / Transaction newTransaction (DataSource dataSource, TransactionIsolationLevel level, boolean autoCommit);}
The main implementation classes are JdbcTransactionFactory and ManagedTransactionFactory. The biggest difference between the two is that ManagedTrandactionFactory will have one more function of whether to close the data source when it is closed. JdbcTransactionFactory is sure to close. Check the corresponding implementation main method.
JdbcTransaction
@ Override public void close () throws SQLException {if (connection! = null) {resetAutoCommit (); if (log.isDebugEnabled ()) {log.debug ("Closing JDBC Connection [" + connection + "]");} connection.close ();}}
ManagedTransaction
Public void close () throws SQLException {if (this.closeConnection & & this.connection! = null) {if (log.isDebugEnabled ()) {log.debug ("Closing JDBC Connection [" + this.connection + "]");} this.connection.close ();}} package org.apache.ibatis.transaction.jdbc;import java.sql.Connection;import java.util.Properties;import javax.sql.DataSource;import org.apache.ibatis.session.TransactionIsolationLevel Import org.apache.ibatis.transaction.Transaction;import org.apache.ibatis.transaction.TransactionFactory;/** * Creates {@ link JdbcTransaction} instances. * * @ author Clinton Begin * * @ see JdbcTransaction * / public class JdbcTransactionFactory implements TransactionFactory {@ Override public void setProperties (Properties props) {} @ Override public Transaction newTransaction (Connection conn) {return new JdbcTransaction (conn);} @ Override public Transaction newTransaction (DataSource ds, TransactionIsolationLevel level, boolean autoCommit) {return new JdbcTransaction (ds, level, autoCommit);}} package org.apache.ibatis.transaction.managed;import java.sql.Connection;import java.util.Properties;import javax.sql.DataSource Import org.apache.ibatis.session.TransactionIsolationLevel;import org.apache.ibatis.transaction.Transaction;import org.apache.ibatis.transaction.TransactionFactory;/** * Creates {@ link ManagedTransaction} instances. * * @ author Clinton Begin * * @ see ManagedTransaction * / public class ManagedTransactionFactory implements TransactionFactory {private boolean closeConnection = true; @ Override public void setProperties (Properties props) {if (props! = null) {String closeConnectionProperty = props.getProperty ("closeConnection"); if (closeConnectionProperty! = null) {closeConnection = Boolean.valueOf (closeConnectionProperty);}} @ Override public Transaction newTransaction (Connection conn) {return new ManagedTransaction (conn, closeConnection) } @ Override public Transaction newTransaction (DataSource ds, TransactionIsolationLevel level, boolean autoCommit) {/ / Silently ignores autocommit and isolation level, as managed transactions are entirely / / controlled by an external manager. It's silently ignored so that / / code remains portable between managed and unmanaged configurations. Return new ManagedTransaction (ds, level, closeConnection);}}
With the data source, you can configure the construction of the environment class. The Environment source code is as follows. The main function of id is to distinguish it from the environment.
/ * Copyright 2009-2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "ASIS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * / package org.apache.ibatis.mapping;import javax.sql.DataSource;import org.apache.ibatis.transaction.TransactionFactory;/** * @ author Clinton Begin * / public final class Environment {private final String id; private final TransactionFactory transactionFactory; private final DataSource dataSource; public Environment (String id, TransactionFactory transactionFactory, DataSource dataSource) {if (id = = null) {throw new IllegalArgumentException ("Parameter 'id' must not be null") } if (transactionFactory = = null) {throw new IllegalArgumentException ("Parameter 'transactionFactory' must not be null");} this.id = id; if (dataSource = = null) {throw new IllegalArgumentException ("Parameter' dataSource' must not be null");} this.transactionFactory = transactionFactory; this.dataSource = dataSource;} public static class Builder {private String id; private TransactionFactory transactionFactory; private DataSource dataSource Public Builder (String id) {this.id = id;} public Builder transactionFactory (TransactionFactory transactionFactory) {this.transactionFactory = transactionFactory; return this;} public Builder dataSource (DataSource dataSource) {this.dataSource = dataSource; return this;} public String id () {return this.id;} public Environment build () {return new Environment (this.id, this.transactionFactory, this.dataSource) }} public String getId () {return this.id;} public TransactionFactory getTransactionFactory () {return this.transactionFactory;} public DataSource getDataSource () {return this.dataSource;}}
The environment, data source, and transaction configuration are constructed into Configuration,Configuaration configuration classes. The mapping relationship of sql is as follows
Public Configuration (Environment environment) {this (); this.environment = environment;} public Configuration () {typeAliasRegistry.registerAlias ("JDBC", JdbcTransactionFactory.class); typeAliasRegistry.registerAlias ("MANAGED", ManagedTransactionFactory.class); typeAliasRegistry.registerAlias ("JNDI", JndiDataSourceFactory.class); typeAliasRegistry.registerAlias ("POOLED", PooledDataSourceFactory.class); typeAliasRegistry.registerAlias ("UNPOOLED", UnpooledDataSourceFactory.class); typeAliasRegistry.registerAlias ("PERPETUAL", PerpetualCache.class) TypeAliasRegistry.registerAlias ("FIFO", FifoCache.class); typeAliasRegistry.registerAlias ("LRU", LruCache.class); typeAliasRegistry.registerAlias ("SOFT", SoftCache.class); typeAliasRegistry.registerAlias ("WEAK", WeakCache.class); typeAliasRegistry.registerAlias ("DB_VENDOR", VendorDatabaseIdProvider.class); typeAliasRegistry.registerAlias ("XML", XMLLanguageDriver.class); typeAliasRegistry.registerAlias ("RAW", RawLanguageDriver.class); typeAliasRegistry.registerAlias ("SLF4J", Slf4jImpl.class) TypeAliasRegistry.registerAlias ("COMMONS_LOGGING", JakartaCommonsLoggingImpl.class); typeAliasRegistry.registerAlias ("LOG4J", Log4jImpl.class); typeAliasRegistry.registerAlias ("LOG4J2", Log4j2Impl.class); typeAliasRegistry.registerAlias ("JDK_LOGGING", Jdk14LoggingImpl.class); typeAliasRegistry.registerAlias ("STDOUT_LOGGING", StdOutImpl.class); typeAliasRegistry.registerAlias ("NO_LOGGING", NoLoggingImpl.class); typeAliasRegistry.registerAlias ("CGLIB", CglibProxyFactory.class); typeAliasRegistry.registerAlias ("JAVASSIST", JavassistProxyFactory.class) LanguageRegistry.setDefaultDriverClass (XMLLanguageDriver.class); languageRegistry.register (RawLanguageDriver.class);}
SqlSessionFactoryBuilder is a builder, and its main function is to convert xml configuration files into Configuration configurations. The main methods are as follows
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. }}}
After the construction of the above classes, the ultimate goal is to obtain the SqlSessionFactory class and construct the SqlSession class. Take the DefaultSqlSessionFactory class as an example, the main construction method of openSession
Private SqlSession openSessionFromDataSource (ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {Transaction tx = null; try {final Environment environment = configuration.getEnvironment (); final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment (environment); tx = transactionFactory.newTransaction (environment.getDataSource (), level, autoCommit); final Executor executor = configuration.newExecutor (tx, execType); 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 ();}}
Executor is an executor interface, the main SimpleExecutor,BatchExecutor,ReuseExecutor,CachingExecutor, respectively dealing with simple, batch, reuse, cache parser
Public Executor newExecutor (Transaction transaction, ExecutorType executorType) {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 SimpleExecutor as an example. When DefaultSqlSession executes a query, MappedStatement contains mapping configuration information.
@ Override public List selectList (String statement, Object parameter, RowBounds rowBounds) {try {MappedStatement ms = configuration.getMappedStatement (statement); return executor.query (ms, wrapCollection (parameter), rowBounds, Executor.NO_RESULT_HANDLER);} catch (Exception e) {throw ExceptionFactory.wrapException ("Error querying database. Cause:" + e, e);} finally {ErrorContext.instance (). Reset ();}}
To execute the query process, prepareStatement acquires the Statement object of Jdbc, executes the query process, encapsulates the return interface, and the whole process is completed.
@ Override public List doQuery (MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {Statement stmt = null; try {Configuration configuration = ms.getConfiguration (); StatementHandler handler = configuration.newStatementHandler (wrapper, ms, parameter, rowBounds, resultHandler, boundSql); stmt = prepareStatement (handler, ms.getStatementLog ()); return handler.query (stmt, resultHandler);} finally {closeStatement (stmt) }} private Statement prepareStatement (StatementHandler handler, Log statementLog) throws SQLException {Statement stmt; Connection connection = getConnection (statementLog); stmt = handler.prepare (connection, transaction.getTimeout ()); handler.parameterize (stmt); return stmt;} is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.
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.