参考了这篇文章:https://www.cnblogs.com/xuwc/p/13993164.html
//step 1
String resource = "mybatis.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
//step 2
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//step 3
SqlSession sqlSession = SessionFactory.openSession();
//step 4
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
- 读取Mybatis的xml核心配置文件,并把它加载成一个输入流
String resource = "mybatis.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
- 让SqlSessinFactoryBuilder构建这个输入流,并返回一个SqlSessionFactory:
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
build(inputStream)调用了SqlSessionFactoryBuilder中的build方法
build(inputStream, null, null);
解析xml文件,生成一个解析器
XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties);
parser.parse():解析器生成一个Configuration对象,里面包含了Mybatis核心配置文件可以配置的属性信息
return build(parser.parse());
根据Configuration类生成一个DefaultSqlSessionFactory对象
- SqlSession sqlSession = SessionFactory.openSession();
调用DefaultSqlSessionFactory返回一个SqlSession对象
返回一个DefaultSqlSession对象
return new DefaultSqlSession(configuration, executor, autoCommit);
- UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
从SqlSession中根据接口的Class对象获取一个接口的实例对象
根据接口的Class对象获得一个Mapper的动态代理的工厂MapperProxyFactory:此工厂用于返回一个Mapper的动态代理的实例MapperProxy
MapperProxy中的invoke方法:
如果是Object对象的方法,直接执行;
如果是接口中的default修饰的具体方法直接执行;
如果是接口中的其他方法(这些其他方法,也就是我们在XXXMapper.xml中配置的方法)从缓存中找到一个MapperMethod对象,没有就新建一个。
MapperMethod的execute方法:
根据不同的Mybatis标签(Insert, Update…)执行具体的SQL语句