承接上文,我们现在已经获得到了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参数,另外一者负责反射设置结果集