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(); } }
可以看到最後回傳一個DefaultSql
r.SqlSession對象,DefaultSqlSession中的selectOne(…) selectList(…)
selectMap(…) update(…)等方法就是真正執行要執行sql的方法
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中文網其他相關文章!