mybatis(三)部分源码解析

1.接口式编程,为什么mybatis可以只定义dao接口(不涉及spring的情况下)即以下代码

public interface CityDao {
    List<City> listCity();
}

从SqlSession的<T> T getMapper(Class<T> type);方法入手,SqlSession的实现类DefaultSqlSession

  // DefaultSqlSession.java
  @Override
  public <T> T getMapper(Class<T> type) {
    return configuration.<T>getMapper(type, this);
  }
  
  // Configuration.java
  public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
    return mapperRegistry.getMapper(type, sqlSession);
  }

  // MapperRegistry.java
    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);
    }
  }

  // mapperProxyFactory 是如何附值的呢,需要看下knownMappers,这个add方法是加载配置时赋值的这里不再赘述
  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<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);
        }
      }
    }
  }

  // MapperProxyFactory<T>.java
  public T newInstance(SqlSession sqlSession) {
    final MapperProxy<T> mapperProxy = new MapperProxy<T>(sqlSession, mapperInterface, methodCache);
    return newInstance(mapperProxy);
  }

  // 最后生成动态代理类
  @SuppressWarnings("unchecked")
  protected T newInstance(MapperProxy<T> mapperProxy) {
    return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
  }

 2.分页拦截器 (前面一部分代码是解释如何能够调用到拦截器进行拦截)

// 拦截器配置到配置文件中,那么Configuration实例中就能拿到拦截器然后是这个方法
public StatementHandler newStatementHandler(Executor executor, MappedStatement mappedStatement, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {
    StatementHandler statementHandler = new RoutingStatementHandler(executor, mappedStatement, parameterObject, rowBounds, resultHandler, boundSql);
    statementHandler = (StatementHandler) interceptorChain.pluginAll(statementHandler);
    return statementHandler;
}
// InterceptorChain的pluginAll方法的执行会调到我们下面实现类中的plugin方法,进而返回代理对象
public Object pluginAll(Object target) {
    for (Interceptor interceptor : interceptors) {
        target = interceptor.plugin(target);
    }
    return target;
}
// 注解表明拦截的是StatementHandler这个类的prepare方法,可以看下PreparedStatementHandler的prepare方法
@Intercepts(@Signature(type = StatementHandler.class, method = "prepare", args = { Connection.class }))
public class PagingInterceptor implements Interceptor{
    
    private final Logger logger = LoggerFactory.getLogger(PagingInterceptor.class);
    
    /** 数据库方言 */
    private MyBatisDialect dialect;

// 调用这个方法的时机,可以看下plugin中动态代理实现类的invoke方法里面会调用 @SuppressWarnings(
"unchecked") @Override public Object intercept(Invocation invocation) throws Throwable { StatementHandler statementHandler = (StatementHandler) invocation.getTarget(); BoundSql boundSql = statementHandler.getBoundSql(); Object paramObj = boundSql.getParameterObject(); if( paramObj instanceof Map ){ Map<String, Object> param = (Map<String, Object>) paramObj; if((param.containsKey("start")||param.containsKey("offset"))&&param.containsKey("limit")) { String startTemp = (String)param.get("start"); if(startTemp == null) { startTemp = (String)param.get("offset"); } String limitTemp = (String)param.get("limit"); if( startTemp!=null && limitTemp!=null ){ Integer start = Integer.parseInt(startTemp); Integer limit = Integer.parseInt(limitTemp); MetaObject metaStatementHandler = MetaObject.forObject(statementHandler, SystemMetaObject.DEFAULT_OBJECT_FACTORY, SystemMetaObject.DEFAULT_OBJECT_WRAPPER_FACTORY); String sql = boundSql.getSql(); //分页sql String pageSql = dialect.getLimitSql(start, limit, sql); logger.debug("封装分页sql:" + pageSql); metaStatementHandler.setValue("delegate.boundSql.sql", pageSql); //重写param参数, 加入total //MappedStatement mappedStatement = (MappedStatement)metaStatementHandler.getValue("delegate.mappedStatement"); Connection connection = (Connection) invocation.getArgs()[0]; if( !param.containsKey("nototal")){ setPageParameter(sql, connection, statementHandler, param); } } } }else if(logger.isDebugEnabled()){ logger.debug("sql:" + boundSql.getSql()); } return invocation.proceed(); } @Override public Object plugin(Object target) { // 当目标类是StatementHandler类型时,才包装目标类,否者直接返回目标本身,减少目标被代理的次数 if (target instanceof StatementHandler) { return Plugin.wrap(target, this); } else { return target; } } private void setPageParameter(String sql, Connection connection, StatementHandler statementHandler, Map<String,Object> param) { if(param.containsKey("total")){ return; } // 记录总记录数 String countSql = dialect.getTotalSql(sql); PreparedStatement countStmt = null; ResultSet rs = null; try { logger.debug("总行数sql:" + countSql); countStmt = connection.prepareStatement(countSql); statementHandler.parameterize(countStmt);//mybatis处理参数的方式 rs = countStmt.executeQuery(); int totalCount = 0; if (rs.next()) { totalCount = rs.getInt(1); } param.put("total", totalCount); } catch (SQLException e) { throw new RuntimeException(e); } finally { JdbcUtils.closeResultSet(rs); JdbcUtils.closeStatement(countStmt); } } @Override public void setProperties(Properties properties) { } //-----------------set get public void setDialect(MyBatisDialect dialect) { this.dialect = dialect; } }

 tips:

需要关注下MetaObject这个类,这个类可以通过反射帮我们实现对StatementHandler的实例属性的存取,value的key支持ognl表达式

转载于:https://www.cnblogs.com/yyyyy-1988/p/10248937.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值