MyBatis实现原理和代码解读

来源:互联网 发布:自学编程从入门到精通 编辑:程序博客网 时间:2024/06/07 02:45

一、流程:

1、首先加载mybatis-config.xml文件;
2、通过读取文件返回InputStream;
3、然后利用SqlSessionFactoryBuilder().build(inputStream)返回SqlSessionFactory对象。
4、使用SqlSessionFactory.openSession();获取SqlSession 对象;
5、sqlSession.getMapper获取映射对象;
6、执行sql;
7、提交:sqlSession.commit();

二、原理:

1、SqlSessionFactoryBuilder()中build方法:

public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) {try {XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties);SqlSessionFactory localSqlSessionFactory = build(parser.parse());return localSqlSessionFactory;} catch (Exception e) {} finally {ErrorContext.instance().reset();try {inputStream.close();} catch (IOException e) {}}}
public SqlSessionFactory build(Configuration config) {return new DefaultSqlSessionFactory(config);}

2SqlSessionFactory.openSession()

private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level,boolean autoCommit) {Transaction tx = null;try {Environment environment = this.configuration.getEnvironment();TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment);tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit);Executor executor = this.configuration.newExecutor(tx, execType);DefaultSqlSession localDefaultSqlSession = new DefaultSqlSession(this.configuration, executor, autoCommit);return localDefaultSqlSession;} catch (Exception e) {throw ExceptionFactory.wrapException("Error opening session.  Cause: " + e, e);} finally {ErrorContext.instance().reset();}}
通过加载配置文件中的environment判断数据库连接是使用哪个连接方式、驱动、地址、用户名、密码


sqlSession接口通过DefaultSqlSession、sqlSessionManager实现

3、sqlSession.getMapper

sqlSession.getMapper通过泛型实现,代码如下:
public <T> T getMapper(Class<T> type) {return this.configuration.getMapper(type, this);    }

4、映射对象进行增删该查。

5、提交

public void commit(boolean force) {try {this.executor.commit(isCommitOrRollbackRequired(force));this.dirty = false;} catch (Exception e) {} finally {ErrorContext.instance().reset();}}





原创粉丝点击