我们已经创建定制好了我们的Configuration文件,它是MyBatis和外界进行交流的途径,并且将配置文件加载到sqlSessionFactoryBuilder中来生成sqlSessionFactory。
Reader reader = Resources.getResourceAsReader("mybatis-config.xml"); sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); reader.close();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
我们从工厂里拿到一个sqlSession,并通过加载Mapper对象的方式来获取到我们所要用的对象,这一块就用到了动态代理,那么MyBatis是怎么来处理这一个动作的呢?这时候就要去源码里一探究竟了。我们执行到上一个代码块的最后一句,然后进去看一看。
@Override public <T> T getMapper(Class<T> type) { return configuration.<T>getMapper(type, this); }
sqlSession中的getMapper方法里面是通过sqlSession里定义的configuration来getMapper的,这个configuration在我生成sqlSession时就已经定义好了。我们可以看一下我们的configuration文件,可以看到我们已经定义好了拥有哪些Mapper。
<mappers> <package name="tk.mybatis.simple.mapper"/> </mappers>
那么configuration是怎样来getMapper的呢?
public <T> T getMapper(Class<T> type, SqlSession sqlSession) { return mapperRegistry.getMapper(type, sqlSession); }
看到源码我们可以得知在方法内部又是通过mapper注册器来调用getMapper方法的。那么我们可以看到他传入的参数又type,那么我们可不可以认为在mapperRegistry内部有一个容器用来存放Mapper呢?再往里走一下看看。
private final Map<Class<?>, MapperProxyFactory<?>> knownMappers = new HashMap<Class<?>, MapperProxyFactory<?>>(); @SuppressWarnings("unchecked") 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); } }
同样我还在里面发现了addMapper方法,说明我们的初步猜想是对的,我们会得到一个动态代理工厂。在往下继续走之前,我们不妨考虑一个问题,那就是在哪里添加我们要取到的东西呢?于是我们可以看一下addMapper方法。
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); } } } }
addMapper方法用到的参数只有type一个,那么只能去看一下到底有哪些地方用到了这个方法。然后我发现我又回到了configuration文件,在同样名为addMapper的方法中调用了这个方法,然后这也解释不了我们的疑问,于是接着往上看,看到了最后的文件,就是XMLConfigBuilder。
1 private void mapperElement(XNode parent) throws Exception { 2 if (parent != null) { 3 for (XNode child : parent.getChildren()) { 4 if ("package".equals(child.getName())) { 5 String mapperPackage = child.getStringAttribute("name"); 6 configuration.addMappers(mapperPackage); 7 } else { 8 String resource = child.getStringAttribute("resource"); 9 String url = child.getStringAttribute("url"); 10 String mapperClass = child.getStringAttribute("class"); 11 if (resource != null && url == null && mapperClass == null) { 12 ErrorContext.instance().resource(resource); 13 InputStream inputStream = Resources.getResourceAsStream(resource); 14 XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, resource, configuration.getSqlFragments()); 15 mapperParser.parse(); 16 } else if (resource == null && url != null && mapperClass == null) { 17 ErrorContext.instance().resource(url); 18 InputStream inputStream = Resources.getUrlAsStream(url); 19 XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, url, configuration.getSqlFragments()); 20 mapperParser.parse(); 21 } else if (resource == null && url == null && mapperClass != null) { 22 Class<?> mapperInterface = Resources.classForName(mapperClass); 23 configuration.addMapper(mapperInterface); 24 } else { 25 throw new BuilderException("A mapper element may only specify a url, resource or class, but not more than one."); 26 } 27 } 28 } 29 } 30 }
可以看到,在第23行调用了configuration的addMapper方法。
我们再回到Mapper注册器这一块,接着往下走,因为我们看到了MapperProxyFactory,我们就可以猜到一定会有一个类叫做MapperProxy,下面有个newInstance方法,我闭着眼睛都能猜到,他会在方法里调用一次MapperProxy的newInstance方法。那就让事实来验证一下我的猜想吧。
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<T>(sqlSession, mapperInterface, methodCache); return newInstance(mapperProxy); }
MyBatis在这里的处理和我想的不是很一样,他先生成一个MapperProxy实例,然后再通过调用Proxy的接口来完成创建Mapper的操作。到这里,我们大概了解到了Mapper对象是怎么创建的了。
这时候我们可以看到我们生成的Mapper对象实质是一个代理类org.apache.ibatis.binding.MapperProxy@3eb738bb。
SysUser user = userMapper.selectById(id);
首先,我们进入方法看一下。
@Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (Object.class.equals(method.getDeclaringClass())) { try { return method.invoke(this, args); } catch (Throwable t) { throw ExceptionUtil.unwrapThrowable(t); } } final MapperMethod mapperMethod = cachedMapperMethod(method); return mapperMethod.execute(sqlSession, args); }
发现我们直接进入到了代理类MapperProxy的invoke方法中,我们可以发现,在代理类中,并没有存在被代理对象,只有一个被代理对象类型mapperInterface,这似乎和我们所熟知的动态代理不是那么一样?那么他到底怎样做的才实现了我们所要的功能呢?这里传入的参数method就是指的selectById。首先我们来看第一句,它的意思是如果这个传入方法的类是Object,那么就可以执行,它的意思就是如果传进来的方法每个类都有,那么就当做这个类是MapperProxy。我们这次的执行肯定不会走if里面的语句,然后接着往下看。对于cacheMapperMethod这个方法,我们可以看一下。
private MapperMethod cachedMapperMethod(Method method) { MapperMethod mapperMethod = methodCache.get(method); if (mapperMethod == null) { mapperMethod = new MapperMethod(mapperInterface, method, sqlSession.getConfiguration()); methodCache.put(method, mapperMethod); } return mapperMethod; }
这个意思就是说,会从methodCache里取出method相关的MapperMethod对象,如果没有取到,也就是MapperMethod为空,他就会根据Configuration创建一个该方法相关的MapperMethod,并将其放入到Cache中,然后返回此MapperMethod。
之后我们回到上一个代码块,它最后返回的事mapperMethod的execute方法,在这里,仿佛看到了胜利的曙光。究竟结果是怎么样的呢?我们要进去看一下。
1 public Object execute(SqlSession sqlSession, Object[] args) { 2 Object result; 3 if (SqlCommandType.INSERT == command.getType()) { 4 Object param = method.convertArgsToSqlCommandParam(args); 5 result = rowCountResult(sqlSession.insert(command.getName(), param)); 6 } else if (SqlCommandType.UPDATE == command.getType()) { 7 Object param = method.convertArgsToSqlCommandParam(args); 8 result = rowCountResult(sqlSession.update(command.getName(), param)); 9 } else if (SqlCommandType.DELETE == command.getType()) { 10 Object param = method.convertArgsToSqlCommandParam(args); 11 result = rowCountResult(sqlSession.delete(command.getName(), param)); 12 } else if (SqlCommandType.SELECT == command.getType()) { 13 if (method.returnsVoid() && method.hasResultHandler()) { 14 executeWithResultHandler(sqlSession, args); 15 result = null; 16 } else if (method.returnsMany()) { 17 result = executeForMany(sqlSession, args); 18 } else if (method.returnsMap()) { 19 result = executeForMap(sqlSession, args); 20 } else { 21 Object param = method.convertArgsToSqlCommandParam(args); 22 result = sqlSession.selectOne(command.getName(), param); 23 } 24 } else if (SqlCommandType.FLUSH == command.getType()) { 25 result = sqlSession.flushStatements(); 26 } else { 27 throw new BindingException("Unknown execution method for: " + command.getName()); 28 } 29 if (result == null && method.getReturnType().isPrimitive() && !method.returnsVoid()) { 30 throw new BindingException("Mapper method '" + command.getName() 31 + " attempted to return null from a method with a primitive return type (" + method.getReturnType() + ")."); 32 } 33 return result; 34 }
因为我们的这个方法的SQL语句是用的Select,所以代码会直接走到12行然后进入,最后到22行的selectOne方法,上一句是把参数转化一下。进入这个方法。
@Override public <T> T selectOne(String statement) { return this.<T>selectOne(statement, null); } @Override public <T> T selectOne(String statement, Object parameter) { // Popular vote was to return null on 0 results and throw exception on too many. List<T> list = this.<T>selectList(statement, parameter); if (list.size() == 1) { return list.get(0); } else if (list.size() > 1) { throw new TooManyResultsException("Expected one result (or null) to be returned by selectOne(), but found: " + list.size()); } else { return null; } }
这时候就发现又回到了sqlSession方法,果然sqlSession作为与外部交流的出入口真的是无所不能。这里我们会发现,我们明明只要一个,他为啥还要去定义一个selectList呢?其实我个人认为这种就是一劳永逸的方法,既然有找一个的需求,那么久会有找多个的需求,只需要在后续定义一下就可以了。然后我们可以看一下SelectList这个方法。
@Override 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); return executor.query(ms, wrapCollection(parameter), rowBounds, Executor.NO_RESULT_HANDLER); } catch (Exception e) { throw ExceptionFactory.wrapException("Error querying database. Cause: " + e, e); } finally { ErrorContext.instance().reset(); } }
最后走到了executor这一块,经过后续的处理,就会得到我们要的结果。