MyBatis如何实现无需实现类直接调用接口

答案是 动态代理

通常我们使用 MyBatis 的主要步骤是:

  1. 构建 SqlSessionFactory
  2. 从 SqlSessionFactory 中获取 SqlSession
  3. 从SqlSession 中获取 mapper
  4. 调用mapper下的方法

代码流程

// 1. 构建SqlSessionFactory
Reader reader = Resources.getResourceAsReader("org/apache/ibatis/submitted/associationtest/mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
// 2. 获取sqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
// 3. 获取mapper
Mapper mapper = sqlSession.getMapper(Mapper.class);
// 4. 调用mapper下的方法
List<Car> cars = mapper.getCars();

主要看第3、第4步
Mapper类如下:

public interface Mapper {
    List<Car> getCars();
}

Mapper是接口, 只有当他有实现类时 才能调用下面的getCars方法。所以肯定是第三步sqlSession.getMapper时 生成了他的实现类。

SqlSession有两个的实现类DefaultSqlSession/SqlSessionManager。getMapper方法都直接调用了Configuration类的getMapper方法

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

org.apache.ibatis.session.Configuration类

public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
    return mapperRegistry.getMapper(type, sqlSession);
  }

mapper注册类 -> MapperRegistry

创建了一个类的全局变量knownMappers用于存入mapper映射,getMapper时 先冲knownMappers里面获取mapperProxyFactory, 再由这个工厂类进行生成Mapper实现类

// 存入mapper映射 其Key 为当前Class对象,value 为一个MapperProxyFactory 实例。
private final Map<Class<?>, MapperProxyFactory<?>> knownMappers = new HashMap<>();

/**
 * 获取mapper
 */
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);
    }
  }

mapper代理实现类工厂 -> MapperProxyFactory

生成代理对象MapperProxy,创建实例

public class MapperProxyFactory<T> {

  private final Class<T> mapperInterface;
  private final Map<Method, MapperMethodInvoker> methodCache = new ConcurrentHashMap<>();

  public MapperProxyFactory(Class<T> mapperInterface) {
    this.mapperInterface = mapperInterface;
  }

  public Class<T> getMapperInterface() {
    return mapperInterface;
  }

  public Map<Method, MapperMethodInvoker> getMethodCache() {
    return methodCache;
  }

  @SuppressWarnings("unchecked")
  protected T newInstance(MapperProxy<T> mapperProxy) {
    return (T) 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);
  }

mapper代理类 -> MapperProxy

实现了InvocationHandler对代理的方法进行拦截

public class MapperProxy<T> implements InvocationHandler, Serializable {
    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 {
        // invoke方法调用MapperProxy.PlainMethodInvoker#invokemapperMethod.execute(sqlSession, args)
        // 根据sqlCommond的类型进行处理,sqlSession.insert/update/select etc.
        return cachedInvoker(method).invoke(proxy, method, args, sqlSession);
      }
    } catch (Throwable t) {
      throw ExceptionUtil.unwrapThrowable(t);
    }
  }
}

关于MapperRegistry

获取SqlSessionFactory的时候上述写法是直接读取xml配置文件的,(也可以代码创建)
xml配置如下:

<configuration>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC">
                <property name="" value="" />
            </transactionManager>
            <dataSource type="UNPOOLED">
                <property name="driver" value="org.hsqldb.jdbcDriver" />
                <property name="url" value="jdbc:hsqldb:mem:basetest" />
                <property name="username" value="sa" />
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper resource="org/apache/ibatis/submitted/associationtest/Mapper.xml" />
    </mappers>

</configuration>

对于mapper文件的注册是,通过MapperRegistry#addMapper方法注册的。缓存在knownMappers变量里面

/**
 * 添加mapper
 */
public <T> void addMapper(Class<T> type) {
    // 只注册接口
    if (type.isInterface()) {
      if (hasMapper(type)) {
        throw new BindingException("Type " + type + " is already known to the MapperRegistry.");
      }
      boolean loadCompleted = false;
      try {
        knownMappers.put(type, new MapperProxyFactory<>(type));
        // It's important that the type is added before the parser is run
        // otherwise the binding may automatically be attempted by the
        // mapper parser. If the type is already known, it won't try.
        // 解析接口以及其对应的xml文件
        MapperAnnotationBuilder parser = new MapperAnnotationBuilder(config, type);
        parser.parse();
        loadCompleted = true;
      } finally {
        if (!loadCompleted) {
          knownMappers.remove(type);
        }
      }
    }
  }
  • 8
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值