MyBatis源码的学习(12)---Mybatis是如何从Mapper.xml中的select到sqlSession.selectList的?

本文详细探讨了MyBatis如何从Mapper.xml中的select标签到sqlSession.selectList的执行过程。涉及到的设计模式包括动态代理、工厂模式、缓存、接口适配器和调用者缓存。通过MapperProxyFactory、MapperMethod和MapperMethodInvoker,MyBatis实现了Java方法与SQL命令的映射,以及对JDK默认方法的支持。整个流程中,缓存机制有效提高了性能,而工厂模式则确保了对象创建的高效性和一致性。

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

这个问题:估计大家都知道是动态代理。可是除了动态代理这之间还有哪些设计模式呢?

    //3、获取mapper
    UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
    //4、执行数据库操作,并处理结果集
    return userMapper.selectUser("10");

先看我们的getMapper方法,是如何返回一个代理对象的。

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

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


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);
    }
  }

先从配置对象configuration中获取,最后委托给mapperRegistry对象。

在mapperRegistry中,有个缓存(knownMappers)对象Map,我们根据key(接口的全限定类名,比如:learn.UserMapper)去获取我们的MapperProxyFactory对象,MapperProxyFactory负责每次创建我们的代理对象的实例。

从这里,我们可以学到缓存和工厂的使用,这样做的好处,很明显,避免了资源的重复加载,可以重复利用我们的资源。

我们的MapperProxyFactory对象是在我们,创建configuration对象的过程中,解析xml生成并缓存起来的。


package org.apache.ibatis.binding;

import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.ibatis.binding.MapperProxy.MapperMethodInvoker;
import org.apache.ibatis.session.SqlSession;

/**
 * @author Lasse Voss
 */
public class MapperProxyFactory<T> {
  //就是我们的接口 比如:learn.UserMapper
  private final Class<T> mapperInterface;
 //用于缓存我们的方法调用,我们的同一个方法每次调用时࿰
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值