关键流程分析:
mybatis首先会解析mybatis-config.xml,解析到后面会有 各个映射文件的解析,解析映射文件时候,会读取到namespace, 将namespace作为key,
存入到 knownMappers.put(type, new MapperProxyFactory<T>(type)); 然后将映射文件里面各个statement标签,就是那些 select insert update标签,
将标签的 id作为key,标签里面的信息内容封装到MappedStatement对象里面, MappedStatement对象作为key存入 mappedStatements.put(ms.getId(), ms);
最后把上面的解析信息都封装到 Configuration 最后得到 DefaultSqlSessionFactory 此对象包含了 Configuration对象,DefaultSqlSessionFactory 是个工厂类,调用里面的 new DefaultSqlSession(configuration, executor, autoCommit); 最终得到 实用的 DefaultSqlSession对象。
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class); 此方法会返回一个StudentMapper接口的代理对象,采用的是动态代理,关键步骤就是里面会根据 StudentMapper.class信息,去knownMappers集合里面找到对应的 MapperProxyFactory工厂类,然后用此工厂类,创建一个 MapperProxy代理对象。
Student student = studentMapper.findStudentById(studId); 由于 studentMapper是一个动态代理对象,会走进 invoke方法,会根据此动态代理对象里面的信息,信息包括接口的全类名和方法名,以及configuration 创建一个 mapperMethod = new MapperMethod(mapperInterface, method, sqlSession.getConfiguration()); 然后就操作此 MapperMethod对象,会根据全类名和方法名组成key 去configration里面 的集合 mappedStatements.get(id); 取出 MappedStatement 有了此对象,就方便了,里面有各种信息,包括Sql, configration,接下来就是jdbc的操作,去数据库里面查询出数据
进入
new SqlSessionFactoryBuilder().build(inputStream)