public <T> voidaddMapper(Class<T> type){ if (type.isInterface()) { //再次判断是否已注册,已注册抛异常 if (hasMapper(type)) { thrownew BindingException("Type " + type + " is already known to the MapperRegistry."); } boolean loadCompleted = false; try { // 维护mapper接口声明和代理类的映射,代理类的工厂类为MapperProxyFactory(工厂类的初始化只是设置接口,代理类的生成后面再看) 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. //以下是使用注解的方式声明sql的解析(目前没使用这种方式,暂不关注) MapperAnnotationBuilder parser = new MapperAnnotationBuilder(config, type); parser.parse(); loadCompleted = true; } finally { if (!loadCompleted) { knownMappers.remove(type); } } } }
public T getObject()throws Exception { //getSqlSession返回为SqlSessionTemplate,详见SqlSessionDaoSupport类 return getSqlSession().getMapper(this.mapperInterface); }
mapper 只是接口, 实现在 xml 中,需要生成一个 java 对象才能对其进行操作。这个匿名对象就是一个实现了 mapper 接口的动态代理对象。下面是创建代理工厂类。
1 2 3 4 5 6 7 8 9 10 11 12 13
public <T> T getMapper(Class<T> type, SqlSession sqlSession){ // 获取代理类的工厂类,在初始化中设置的 final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type); if (mapperProxyFactory == null) thrownew BindingException("Type " + type + " is not known to the MapperRegistry."); try {