Mybatis源码解析(一)启动及加载
2019-08-26 本文已影响0人
三斤牛肉
先上一段最简单的加载代码:
public static void main(String[] args) {
SqlSession sqlSession = null;
try {
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 查询数据库内容
sqlSession = sqlSessionFactory.openSession();
User user = sqlSession.selectOne("test.user",1);
System.out.println(user);
// 插入数据库内容
} catch (IOException e) {
e.printStackTrace();
}finally {
if (sqlSession != null) {
sqlSession.close();
}
}
}
SqlSessionFactory构造:
public SqlSessionFactory build(Configuration config) {
return new DefaultSqlSessionFactory(config);
}
核心配置:Configuration
至于如何生成的Configuration就不展开了,从xml,注解中解析,或者给默认配置项。
再看如何创建一个sqlSession:
DefaultSqlSessionFactory
@Override
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);
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:执行一个最简单的select操作
@Override
public <E> List<E> 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();
}
}
其实很简单了,通过executor去执行,具体执行器中怎么执行的,后面再讲。