一、Mybatis中Sql执行过程
大家都知道mybatis执行sql,最终是通过sqlSession来执行的。
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
List<Student> studentList = mapper.selectByName("点点");
内部的执行流程如下
可以看到最后通过动态代理构建了一个对象。mapperproxy
mapperProxy又是怎么执行的呢?
详细流程,可以参考这篇文章 MyBatis的SQL执行过程
二、如何实现多数据源配置
在mybatis执行流程中,可以看到sqlSessionFactory 创建sqlSession。而在SpringBoot中sqlSessionFactoryBean中创建sqlSessionFactory ,并且提供了设置数据源的功能。
所以我们要做的是两点
1.替换原有的DefaultSqlSessionFactory
2.设置动态数据源
springbtoot中提供了AbstractRoutingDataSource抽象类,可以实现动态数据源的配置
我们只需要重新determineCurrentLookupKey方法,去读threadlocal中我们保存的数据源。
在写一个选择器用来设置往threadlocal保存数据源。再写一个注解动态的调用选择器设置数据源
demo放在主页了可以下载