mybatis执行流程解析
- mybatis已sqlsession作为顶层API,供外部调用
- sqlsession默认实现DefaultSqlSession,实现增删改查等功能
- 以selectList接口为例:
- MappedStatement ms = configuration.getMappedStatement(statement);
- 通过configuration获取MappedStatement,里面包含了mapper接口的动态代理实现类
- 通过BaseExecutor.query->SimpleExecutor.doQuery之后会生成StatementHandler声明式处理器,得到具体实现,实现内部赌赢应的jdbc的Syatement实现,之后低氧ParameterHandle和TypeHandle,对参数和类型进行处理,最后会调用jdbc的接口查询,之后调用resultSetHandler对查询结果进行类型映射等处理。
- 从以上流程可以得到几个关键点:sqlsession怎么得到,mapper接口动态实现类怎么实现。
sqlsession
sqlsession通过SqlSessionFactory的openSession接口获取,SqlSessionFactory有一个默认实现类:DefaultSqlSessionFactory
openSession内部调用openSessionFromDataSource的得到一个sqlsession实例
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();
}
}
mapper接口
先看一张mapper接口的调用流程图
通过sqlsession的getMapper接口得到mapper接口实现类,内部调用Configuration.getMapper方法,在调用mapperRegistry.getMapper,代码实现如下:
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
//从已加载的MapperProxyFactory从获取MapperProxyFactory,通过addMapper设置
final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type);
if (mapperProxyFactory == null) {
throw new BindingException("Type " + type + " is not known to the MapperRegistry.");
}
try {
//得到mapper接口动态实现实例
return mapperProxyFactory.newInstance(sqlSession);
} catch (Exception e) {
throw new BindingException("Error getting mapper instance. Cause: " + e, e);
}
}
继续看下mapperProxyFactory.newInstance(sqlSession)的实现
protected T newInstance(MapperProxy<T> mapperProxy) {
return (T)
//jdk动态代理生成代理类
Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
}
public T newInstance(SqlSession sqlSession) {
final MapperProxy<T> mapperProxy = new MapperProxy<>(sqlSession, mapperInterface, methodCache);
return newInstance(mapperProxy);
}
可以很清晰的看到内部是基于jdk动态代理技术来生成代理实现类的,其中有三个参数:
- mapperInterface.getClassLoader():mapper接口类加载器
- new Class[] { mapperInterface }:需代理的mapper接口
- mapperProxy:MapperProxy对象,实现了InvocationHandler接口,表示的是当我这个动态代理对象在调用方法的时候,会关联到哪一个InvocationHandler对象上
现在我们只需要看下MapperProxy内部的实现,就可以搞明白是怎么通过mapper实现sql操作的了:
直接看invoke方法:
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
if (Object.class.equals(method.getDeclaringClass())) {
return method.invoke(this, args);
} else if (method.isDefault()) {
if (privateLookupInMethod == null) {
return invokeDefaultMethodJava8(proxy, method, args);
} else {
return invokeDefaultMethodJava9(proxy, method, args);
}
}
} catch (Throwable t) {
throw ExceptionUtil.unwrapThrowable(t);
}
final MapperMethod mapperMethod = cachedMapperMethod(method);
//这行代码mapper到sql操作的映射
return mapperMethod.execute(sqlSession, args);
}
看下这个方法吧:
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:
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);
if (method.returnsOptional()
&& (result == null || !method.getReturnType().equals(result.getClass()))) {
result = Optional.ofNullable(result);
}
}
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;
}
很清晰的可以看到是通过command.getType()判断是curd的什么操作,然后执行相应的逻辑,最终调用的是sqlsession的接口,比如sqlSession.selectList方法
业务方调用mapper接口时,实际调用的是mapper接口的动态代理实现类,通过MapperProxy拦截方法,内部调用MapperMethod.execute实现sql操作