實習日誌(2)mybatis-執行SQL
阿新 • • 發佈:2018-12-09
承接上文,我們現在已經獲得到了SqlSessionFactory物件
public SqlSessionFactory build(Configuration config) {
return new DefaultSqlSessionFactory(config);
}
繼續我們的旅程,
SqlSession session = sqlSessionFactory.openSession()
在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(); } }
由兩個關注點,一個是executor的生成另外一個就是事務的管理。
環境來自xml環境標籤的配置,看上文xml的解析,和其他標籤的解析沒有本質區別 ,
這裡我是用的是JdbcTransaction,返回預設SqlSession,繼續往下看
RoleInfoMapper roleInfoMapper = session.getMapper(RoleInfoMapper.class); 在DefaultSqlSession中 @Override public <T> T getMapper(Class<T> type) { return configuration.<T>getMapper(type, this); } Configuration.java public <T> T getMapper(Class<T> type, SqlSession sqlSession) { return mapperRegistry.getMapper(type, sqlSession); } // 省略部分程式碼 最終 會來到: @SuppressWarnings("unchecked") protected T newInstance(MapperProxy<T> mapperProxy) { return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy); } 是不是很眼熟,之前解析xml的時候就把每個mapper檔案註冊進入了mapperRegistry,現在只要按照key取出來然後使用jdk的動態代理就好了,這個代理物件
下面進入最重要的部分:MapperProxy
MapperProxy
不瞭解jdk動態代理的可以先搜尋一下invokerHandler
public class MapperProxy<T> implements InvocationHandler, Serializable { private static final long serialVersionUID = -6424540398559729838L; private final SqlSession sqlSession; private final Class<T> mapperInterface; // 就是我們寫的 介面,在這裡就是roleInfoMapper private final Map<Method, MapperMethod> methodCache; // 快取 @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { try { if (Object.class.equals(method.getDeclaringClass())) { //如果 是從object繼承來的方法直接忽略 return method.invoke(this, args); } else if (isDefaultMethod(method)) { // 如果是定義在介面中的預設方法,一般也不會這麼做 return invokeDefaultMethod(proxy, method, args); } } catch (Throwable t) { throw ExceptionUtil.unwrapThrowable(t); } final MapperMethod mapperMethod = cachedMapperMethod(method); // 委託給 MapperMethod來執行 return mapperMethod.execute(sqlSession, args); } }
這裡用到的應該 是設計模式中的命令 模式(
有三種角色,一般來說 有一個命令 介面,命令介面中持有一個實際呼叫者引用,每一個命令都實際委託給實際呼叫者,高層例項化 好實際呼叫者只要 不斷呼叫命令 即可
)。這裡就是這樣,命令就是mapperMethod
實際呼叫是sqlsession
public MapperMethod(Class<?> mapperInterface, Method method, Configuration config) {
this.command = new SqlCommand(config, mapperInterface, method);
this.method = new MethodSignature(config, mapperInterface, method);
}
public Object execute(SqlSession sqlSession, Object[] args) {
Object result;
switch (command.getType()) {
case INSERT: {
Object param = method.convertArgsToSqlCommandParam(args);
result = rowCountResult(sqlSession.insert(command.getName(), param));
break;
}
case UPDATE: {
Object param = method.convertArgsToSqlCommandParam(args);
result = rowCountResult(sqlSession.update(command.getName(), param));
break;
}
case DELETE: {
Object param = method.convertArgsToSqlCommandParam(args);
result = rowCountResult(sqlSession.delete(command.getName(), param));
break;
}
case SELECT: // **本例是進入此,且進入returnMany分支**
if (method.returnsVoid() && method.hasResultHandler()) {
executeWithResultHandler(sqlSession, args);
result = null;
} else if (method.returnsMany()) {
result = executeForMany(sqlSession, args);
} else if (method.returnsMap()) {
result = executeForMap(sqlSession, args);
} else if (method.returnsCursor()) {
result = executeForCursor(sqlSession, args);
} else {
Object param = method.convertArgsToSqlCommandParam(args);
result = sqlSession.selectOne(command.getName(), param);
}
break;
case FLUSH:
result = sqlSession.flushStatements();
break;
default:
throw new BindingException("Unknown execution method for: " + command.getName());
}
if (result == null && method.getReturnType().isPrimitive() && !method.returnsVoid()) {
throw new BindingException("Mapper method '" + command.getName()
+ " attempted to return null from a method with a primitive return type (" + method.getReturnType() + ").");
}
return result;
}
在mapperMethod中 控制了 流程,具體還是讓sqlSession做,
sqlSession select*起頭 的方法最終 都會交給executor.query,這裡的模板方法 ,經由
會先呼叫 父類 的query,再由父類的query 呼叫 子類的doQuery
@Override
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();
}
}
@Override
public <E> List<E> doQuery(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
Statement stmt = null;
try {
Configuration configuration = ms.getConfiguration();
StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql);
// 在這裡我要多說一點,這裡是和事務有關係的,JdbcTransaction不僅僅負責事務管理還負責了資料庫連線的獲取,在這裡會呼叫JdbcTransaction獲取資料庫連線,而此時,自動提交已經被 關閉了
stmt = prepareStatement(handler, ms.getStatementLog());
return handler.<E>query(stmt, resultHandler);
} finally {
closeStatement(stmt);
}
}
此處executor 和 statmentHandler發生聯絡,statmentHandler負責排程另外其他兩大物件resultSetHandler和parameterHandler,一者負責預編譯sql引數,另外一者負責反射設定結果集