mybatis封装了jdbc操作数据库的代码,通过sqlsession来执行sql语句,那么首先来看看mybatis是怎么创建sqlsession。
mybatis没有托管给spring的时候,数据库的配置信息是在configuration.xml文件里边配置的 ,测试代码如下
1 Reader reader = Resources.getResourceAsReader("Configuration.xml");Mybatis通过SqlSessionFactoryBuilder.build(Reader reader)方法创建一个SqlSessionFactory对象 build方法的参数就是刚才的reader对象,里边包含了配置文件的所有信息,build方法有很多重载方法
public SqlSessionFactory build(Reader reader, String environment, Properties properties) {
try {
//委托XMLConfigBuilder来解析xml文件,并构建
XMLConfigBuilder parser = new XMLConfigBuilder(reader, environment, properties);
return build(parser.parse());
} catch (Exception e) {
throw ExceptionFactory.wrapException("Error building SqlSession.", e);
} finally {
ErrorContext.instance().reset();
try {
reader.close();
} catch (IOException e) {
}
public SqlSessionFactory build(Configuration config) {
return new DefaultSqlSessionFactory(config);
}最后返回一个DefaultSqlSessionFactory对象,通过DefaultSqlSessionFactory的openSession()返回一个SqlSession对象
public SqlSession openSession() {
return openSessionFromDataSource(configuration.getDefaultExecutorType(), null, false);
}
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);
//然后产生一个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();
}
}可以看到最后返回一个DefaultSqlSession即SqlSession对象,DefaultSqlSession中的selectOne(…) selectList(…)
selectMap(…) update(…)等方法就是真正执行要执行sql的方法
具体的执行由executor对象来执行
public void select(String statement, Object parameter, RowBounds rowBounds, ResultHandler handler) {
try {
MappedStatement ms = configuration.getMappedStatement(statement);
executor.query(ms, wrapCollection(parameter), rowBounds, handler);
} catch (Exception e) {
throw ExceptionFactory.wrapException("Error querying database. Cause: " + e, e);
} finally {
ErrorContext.instance().reset();
}
}以上就是MyBatis源码学习之SqlSession创建的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号