在此声明,此文章是对江荣波老师的《MyBatis3源码深度解析》的总结,尊重原作者。
分析过程
我们先来看一串代码。
@Test
public void testDynamicSql() throws IOException {
// 获取配置文件输入流
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
// 通过SqlSessionFactoryBuilder的build()方法创建SqlSessionFactory实例
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 调用openSession()方法创建SqlSession实例
SqlSession sqlSession = sqlSessionFactory.openSession();
// 获取UserMapper代理对象
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
UserEntity entity = new UserEntity();
entity.setPhone("18700001111");
List<UserEntity> userList = userMapper.getUserByEntity(entity);
System.out.println(JSON.toJSONString(userList));
}
我们可以看到,要查询userList,我们得先调用SqlSession的getMapper()方法获取到UserMapper,但是UserMapper只是一个接口,所以getMapper()方法获取到的实例到底是什么呢?我们通过debug可以看到获取到的是一个动态代理对象MapperProxy。
下面是相关源代码
public class MapperProxy<T> implements InvocationHandler, Serializable {
private static final long serialVersionUID = -6424540398559729838L;
private final SqlSession sqlSession;
private final Class<T> mapperInterface;
private final Map<Method, MapperMethod> methodCache;
public MapperProxy(SqlSession sqlSession, Class<T> mapperInterface, Map<Method, MapperMethod> methodCache) {
this.sqlSession = sqlSession;
this.mapperInterface = mapperInterface;
this.methodCache = methodCache;
}
@Override
public Object invoke