1、Spring 通过 MybatisProperties 配置MybatisAutoConfiguration
2、创建DefaultSqlSessionFactory,从而创建SqlSession
3、动态代理类的生成,sql语句的执行
1.当我们调用DefaultSqlSession的getMapper方法时,都会创建一个新的动态代理类实例,
2.方法:sqlSession.getMapper(*Mapper.class);而SqlSession对象又将getMapper方法委给了
Configuration对象执行
public class DefaultSqlSession implements SqlSession {
private Configuration configuration;
@Override
public <T> T getMapper(Class<T> type) {
return configuration.<T>getMapper(type, this);
}
}
3.通过Configuration类里面通过MapperRegistry对象生成动态代理类的***Mapper接口信息。
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
return mapperRegistry.getMapper(type, sqlSession);
}
@SuppressWarnings("unchecked")
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>)
knownMappers.get(type);
if (mapperProxyFactory == null) {
throw new BindingException("Type " + type + " is not known to the
MapperRegistry.");
}
try {
return mapperProxyFactory.newInstance(sqlSession);
} catch (Exception e) {
throw new BindingException("Error getting mapper instance. Cause: " + e, e);
}
}
4.通过MapperProxyFactory<T> 生成代理对象
/**
* @author Lasse Voss
*/
public class MapperProxyFactory<T> {
------
@SuppressWarnings("unchecked")
protected T newInstance(MapperProxy<T> mapperProxy) {
return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] {
mapperInterface }, mapperProxy);
}
5.通过MapperProxy<T> invoke执行方法
public class MapperProxy<T> implements InvocationHandler, Serializable {
--------
@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);
return mapperMethod.execute(sqlSession, args);
}
}
6.mapperMethod.execute方法解析参数执行sql返回结果