文章目录
Mapper方法调用过程
Mapper方法调用时序
@Test
public void testMybatis() throws IOException, SQLException {
BaseDataTest.createBlogDataSource();
InputStream inputStream = Resources.getResourceAsStream("MapperConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
CachedAuthorMapper cachedAuthorMapper = sqlSession.getMapper(CachedAuthorMapper.class);
cachedAuthorMapper.selectAuthorWithInlineParams(1);
}
使用Mybatis框架执行sql语句,在获取到sqlSession对象后,会调用getMapper方法根据自己定义的Mapper接口获取Mybatis为我们生成的动态代理对象,即MapperProxy。当我们调用Mapper接口的方法时,例如上面的selectAuthorWithInlineParams方法时会被MapperProxy拦截,进而执行invoke方法,在此方法中会调用MapperMethod的execute方法执行sql。在execute方法中,会调用SqlCommand对象的getType方法获取sql语句的类型,调用MethodSignature对象的resolveReturnType获取方法返回值类型,调用convertArgsToSqlCommandParam解析Mapper方法参数,最后根据sql语句类型调用SqlSession的对应方法执行sql语句。
MapperProxy拦截目标方法执行
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
// 从Object类继承的方法不做处理
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);
}
// 对Mapper接口中定义的方法进行封装,生成MapperMethod对象
final MapperMethod mapperMethod = cachedMapperMethod(method);
return mapperMethod.execute(sqlSession, args);
}
MapperMethod的execute方法
public Object execute(SqlSession sqlSession, Object[] args) {
Object result;
// 获取sql语句的类型
switch (command.getType()) {
case INSERT: {
// 获取参数信息
Object param = method.convertArgsToSqlCommandParam(args);
result = rowCountResult(sqlSession.insert(command.getName(), param));
break;