MyBatis 学习笔记(三)运行原理,获取mapper代理对象

这篇博客详细介绍了MyBatis的运行原理,重点在于如何通过Configuration获取Mapper,然后在MapperRegistry中查找,接着由MapperProxyFactory创建MapperProxy,最终形成代理对象,以便执行SQL操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

MyBatis 学习笔记(三)运行原理,获取mapper代理对象

获取接口的代理对象(MapperProxy) getMapper,使用MapperProxyFactory创建一个MapperProxy的代理对象 代理对象里面包含了,DefaultSqlSession(Executor)

//3、获取接口的实现类对象
//会为接口自动的创建一个代理对象,代理对象去执行增删改查方法
DeptMapper deptMapper = (DeptMapper) session.getMapper(DeptMapper.class);
//返回org.apache.ibatis.binding.MapperProxy@610f7aa

1、从configuration获取mapper

public <T> T getMapper(Class<T> type) {
    return configuration.<T>getMapper(type, this);
}

2、在mapperRegistry中获取mapper

knownMappers中保存了所有的,mapper代理对象

public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
  return mapperRegistry.getMapper(type, sqlSession);
}
//从knownMappers 中获取 MapperProxyFactory,这个是在初始化时候已经创建了
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 {
        //创建MapperProxy
        return mapperProxyFactory.newInstance(sqlSession);
    } catch (Exception e) {
        throw new BindingException("Error getting mapper instance. Cause: " + e, e);
    }
}

3、MapperProxyFactory创建MapperProxy

public class MapperProxy<T> implements InvocationHandler, Serializable {
}
//InvocationHandler java动态代理
public T newInstance(SqlSession sqlSession) {
    final MapperProxy<T> mapperProxy = new MapperProxy<T>(sqlSession, mapperInterface, methodCache);
    return newInstance(mapperProxy);
}

4、创建代理对象MapperProxy

//7、创建代理对象MapperProxy
protected T newInstance(MapperProxy<T> mapperProxy) {
    return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
    //mapperInterface=interface com.willow.dao.mapper.DeptMapper
}

5、getMapper运行流程图

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值