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);}
2、SqlSessionFactory.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();}}
阅读全文
1 0
- MyBatis实现原理和代码解读
- SpringMVC实现原理和代码解读
- CNN原理和代码解读【未完待续】
- yolo v2 损失函数源码(训练核心代码)解读和其实现原理
- MyBatis插件原理-源码解读
- 神经网络之激活函数 dropout原理解读 BatchNormalization 代码实现
- HashMap实现原理解读
- PendingIntent实现原理和代码
- PendingIntent实现原理和代码
- PendingIntent实现原理和代码
- Mybatis 代码流程及实现原理解析(一)
- Mybatis 代码流程及实现原理解析(二)
- Mybatis 代码流程及实现原理解析(三)
- Mybatis-Spring实现原理
- mybatis实现原理
- Mybatis实现原理
- mybatis分页原理实现
- mybatis实现原理
- Java学习笔记之集合(七):Map集合的方法
- android吐司
- android获取ros数据
- 汽车ABS结构和工作原理分析
- 解决sping 定时任务在tomcat发布时执行2次的问题
- MyBatis实现原理和代码解读
- js&ajax 替换CKEDITOR中的值
- Inception-v4, Inception-ResNet and the Impact of Residual Connections on Learning论文笔记
- java继承和多态
- 阿里云oss对象存储图片上传
- 背包九讲
- MVC源码学习:打造自己的MVC框架(一:核心原理)
- Vue之Animate
- thinkphp加载数据库图片路径问题