MyBatis底层实现(一)接口和XML的映射

本文探讨了MyBatis在实现数据库操作时的两种方式:配置mapper.xml文件并通过专有API,以及接口与XML的映射。在映射过程中,XML配置会被加载到内存生成mappedStatem对象,接口则通过动态代理实现。MapperMethod类的execute方法在执行时根据不同的操作类型(如insert、delete、update、select)进行处理。

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

我们学习Mybatis时学过三种方式来实现MyBatis操作数据库

一、配置mapper.xml文件然后使用专有的API  

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper  
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"  
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">  
    <select id="selectAll" parameterType="map" resultType="com.mybatis.vo.User">
        select *from user where username like '%${username}%';
        <!-- 
        name like"%"#{name}"%"
        name like '%${name}%'
         name likeconcat(concat('%',#{username}),'%')
         name like CONCAT('%','${name}','%')
         name like '%'||#{name}||'%'
          -->
    </select>
</mapper>  
	@org.junit.Test
	public void testFindall() throws IOException {
		//1.获取sqlSessionFactory对象
        SqlSessionFactory sqlSessionFactory=getSqlSessionFactory();
        //2.获取sqlSession对象
        SqlSession openSession=sqlSessionFactory.openSession();
        Map<String,String> map=new HashMap<>();
        map.put("username", "三");
        try {
        	List<User> list=openSession.selectList("com.mybatis.dao.UserMapper.selectAll",map);
            for(User user:list) {
            	System.out.println(user.getUsername());
            }
        }finally {
            openSession.close();
        }
	}

然后你会想为什么会这么写  底层是如何实现的

 public <E> List<E> selectList(String statement) {
    return this.selectList(statement, null);
  }

  @Override
  public <E> List<E> selectList(String statement, Object parameter) {
    return this.selectList(statement, parameter, RowBounds.DEFAULT);
  }

  @Override
  public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) {
    try {
      MappedStatement ms = configuration.getMappedStatement(statement);//通过statement在Configuration中查找到对应的MapperStatement
      return executor.query(ms, wrapCollection(parameter), rowBounds, Executor.NO_RESULT_HANDLER);//将任务委托给Execute执行器 
    } catch (Exception e) {
      throw ExceptionFactory.wrapException("Error querying database.  Cause: " + e, e);
    } finally {
      ErrorContext.instance().reset();
    }
  }

加载到内存中会生成mappedStatem对象   key为mapper中的id    value为生成的mappedStatem

public <E> List<E> query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler) throws SQLException {
    BoundSql boundSql = ms.getBoundSql(parameter);
    CacheKey key = createCacheKey(ms, parameter, rowBounds, boundSql);
    return query(ms, parameter, rowBounds, resultHandler, key, boundSql);
 }

  @SuppressWarnings("unchecked")
  @Override
  public <E> List<E> query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException {
    ErrorContext.instance().resource(ms.getResource()).activity("executing a query").object(ms.getId());
    if (closed) {
      throw new ExecutorException("Executor was closed.");
    }
    if (queryStack == 0 && ms.isFlushCacheRequired()) {
      clearLocalCache();
    }
    List<E> list;
    try {
      queryStack++;
      list = resultHandler == null ? (List<E>) localCache.getObject(key) : null;
      if (list != null) {
        handleLocallyCachedOutputParameters(ms, key, parameter, boundSql);
      } else {
        list = queryFromDatabase(ms, parameter, rowBounds, resultHandler, key, boundSql);
      }
    } finally {
      queryStack--;
    }
    if (queryStack == 0) {
      for (DeferredLoad deferredLoad : deferredLoads) {
        deferredLoad.load();
      }
      // issue #601
      deferredLoads.clear();
      if (configuration.getLocalCacheScope() == LocalCacheScope.STATEMENT) {
        // issue #482
        clearLocalCache();
      }
    }
    return list;
  }

parameter参数的处理

public void setParameters(PreparedStatement ps) {
    ErrorContext.instance().activity("setting parameters").object(mappedStatement.getParameterMap().getId());
List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
//判断参数
    if (parameterMappings != null) {
      for (int i = 0; i < parameterMappings.size(); i++) {
        ParameterMapping parameterMapping = parameterMappings.get(i);
        if (parameterMapping.getMode() != ParameterMode.OUT) {
          Object value;
          String propertyName = parameterMapping.getProperty();
          if (boundSql.hasAdditionalParameter(propertyName)) { // issue #448 ask first for additional params
            value = boundSql.getAdditionalParameter(propertyName);
          } else if (parameterObject == null) {
            value = null;
          } else if  (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
            value = parameterObject;
          } else {
            MetaObject metaObject = configuration.newMetaObject(parameterObject);
            value = metaObject.getValue(propertyName);
          }
          TypeHandler typeHandler = parameterMapping.getTypeHandler();
          JdbcType jdbcType = parameterMapping.getJdbcType();
          if (value == null && jdbcType == null) {
            jdbcType = configuration.getJdbcTypeForNull();
          }
          try {
            typeHandler.setParameter(ps, i + 1, value, jdbcType);
          } catch (TypeException e) {
            throw new TypeException("Could not set parameters for mapping: " + parameterMapping + ". Cause: " + e, e);
          } catch (SQLException e) {
            throw new TypeException("Could not set parameters for mapping: " + parameterMapping + ". Cause: " + e, e);
          }
        }
      }
    }
  }

二、接口与xml的映射

1)注册代理接口,创建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 {
/放到map中, value为创建代理的工厂
        knownMappers.put(type, new MapperProxyFactory<T>(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.
//解析接口里面的注解        
MapperAnnotationBuilder parser = new MapperAnnotationBuilder(config, type);
        parser.parse();
        loadCompleted = true;
      } finally {
        if (!loadCompleted) {
          knownMappers.remove(type);
        }
      }
    }
  }

2)创建接口动态类

public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
//取出mapperProxyFactory
    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);
    }

3)pper namespace="....">的namespace属性值,判断有没有这样一个接口的全路径与namespace属性值完全相同,如果有,就生成这个接口的动态代理类。

public void parse() {
  if (!configuration.isResourceLoaded(resource)) {
//解析映射文件的根节点mapper元素
configurationElement(parser.evalNode("/mapper"));
configuration.addLoadedResource(resource);
//这个方法内部会根据namespace属性值,生成动态代理类
    bindMapperForNamespace();。
  }
  parsePendingResultMaps();
  parsePendingChacheRefs();
 parsePendingStatements();

4)调用代理方法  进入到   invoke

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    try {
      if (Object.class.equals(method.getDeclaringClass())) {
        return method.invoke(this, args);
      } else if (isDefaultMethod(method)) {
        return invokeDefaultMethod(proxy, method, args);
      }
    } catch (Throwable t) {
      throw ExceptionUtil.unwrapThrowable(t);
    }
final MapperMethod mapperMethod = cachedMapperMethod(method);
//执行相应sql语句
    return mapperMethod.execute(sqlSession, args);
  }

5)最终的拦截代码位于MapperMethod类的execute方法中判断是使用insert|delete|update|select 还有selectOne  selectList  selectMap

public class MapperMethod {
  private final SqlCommand command;
  private final MethodSignature method;
  public MapperMethod(Class<?> mapperInterface, Method method, Configuration config) {
    this.command = new SqlCommand(config, mapperInterface, method);
    this.method = new MethodSignature(config, mapperInterface, method);
  }
  public Object execute(SqlSession sqlSession, Object[] args) {
    Object result;
    if (SqlCommandType.INSERT == command.getType()) {
      Object param = method.convertArgsToSqlCommandParam(args);
      result = rowCountResult(sqlSession.insert(command.getName(), param));
    } else if (SqlCommandType.UPDATE == command.getType()) {
      Object param = method.convertArgsToSqlCommandParam(args);
      result = rowCountResult(sqlSession.update(command.getName(), param));
   } else if (SqlCommandType.DELETE == command.getType()) {
      Object param = method.convertArgsToSqlCommandParam(args);
      result = rowCountResult(sqlSession.delete(command.getName(), param));
    } else if (SqlCommandType.SELECT == command.getType()) {//select语句的处理逻辑
        //根据调用的XxxMapper接口定义的抽象方法的返回值类型,选择SqlSession的不同的方法进行执行。
      if (method.returnsVoid() && method.hasResultHandler()) {
        executeWithResultHandler(sqlSession, args);
        result = null;
      } else if (method.returnsMany()) {//如果方法的返回值是一个集合,调用selectList方法
        result = executeForMany(sqlSession, args);
      } else if (method.returnsMap()) {//如果方法的返回值是一个Map,调用selectMap方法
        result = executeForMap(sqlSession, args);
      } else if (method.returnsCursor()) {//如果方法的返回值,调用selectCurs方法
        result = executeForCursor(sqlSession, args);
      } else {//否则调用sqlSession.selectOne方法
        Object param = method.convertArgsToSqlCommandParam(args);
        result = sqlSession.selectOne(command.getName(), param);
      }
    } else if (SqlCommandType.FLUSH == command.getType()) {
        result = sqlSession.flushStatements();
    } else {
      throw new BindingException("Unknown execution method for: " + command.getName());
    }
    if (result == null && method.getReturnType().isPrimitive() && !method.returnsVoid()) {
      throw new BindingException("Mapper method '" + command.getName() 
          + " attempted to return null from a 
          method with a primitive return type (" + method.getReturnType() + ").");
    }
    return result;
  }
...
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值