
作者:小傅哥
博客:https://bugstack.cn
沉淀、分享、成長,讓自己和他人都能有所識訓!😄
一、前言
Mybatis 最核心的原理也是它最便于使用的體現,為什么這說?
因為我們在使用 Mybatis 的時候,只需要定義一個不需要寫實作類的介面,就能通過注解或者配置SQL陳述句的方式,對資料庫進行 CRUD 操作,
那么這是怎么做到的呢,其中有一點非常重要,就是在 Spring 中可以把你的代理物件交給 Spring 容器,這個代理物件就是可以當做是 DAO 介面的具體實作類,而這個被代理的實作類就可以完成對資料庫的一個操作,也就是這個封裝程序被稱為 ORM 框架,
說了基本的流程,我們來做點測驗,讓大家可以動手操作起來!學知識,一定是上手,才能得到!你可以通過以下原始碼倉庫進行練習
原始碼:https://github.com/fuzhengwei/CodeGuide/wiki
二、把Bean塞到Spring容器,分幾步

- 關于Bean注冊的技術場景,在我們日常用到的技術框架中,MyBatis 是最為常見的,通過在使用 MyBatis 時都只是定義一個介面不需要寫實作類,但是這個介面卻可以和配置的 SQL 陳述句關聯,執行相應的資料庫操作時可以回傳對應的結果,那么這個介面與資料庫的操作就用到的 Bean 的代理和注冊,
- 我們都知道類的呼叫是不能直接呼叫沒有實作的介面的,所以需要通過代理的方式給介面生成對應的實作類,接下來再通過把代理類放到 Spring 的 FactoryBean 的實作中,最后再把這個 FactoryBean 實作類注冊到 Spring 容器,那么現在你的代理類就已經被注冊到 Spring 容器了,接下來就可以通過注解的方式注入到屬性中,
按照這個實作方式,我們來操作一下,看看一個 Bean 的注冊程序在代碼中是如何實作的,
1. 定義介面
public interface IUserDao {
String queryUserInfo();
}
- 先定義一個類似 DAO 的介面,基本這樣的介面在使用 MyBatis 時還是非常常見的,后面我們會對這個介面做代理和注冊,
2. 類代理實作
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
Class<?>[] classes = {IUserDao.class};
InvocationHandler handler = (proxy, method, args) -> "你被代理了 " + method.getName();
IUserDao userDao = (IUserDao) Proxy.newProxyInstance(classLoader, classes, handler);
String res = userDao.queryUserInfo();
logger.info("測驗結果:{}", res);
- Java 本身的代理方式使用起來還是比較簡單的,用法也很固定,
- InvocationHandler 是個介面類,它對應的實作內容就是代理物件的具體實作,
- 最后就是把代理交給 Proxy 創建代理物件,
Proxy.newProxyInstance,
3. 實作Bean工廠
public class ProxyBeanFactory implements FactoryBean {
@Override
public Object getObject() throws Exception {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
Class[] classes = {IUserDao.class};
InvocationHandler handler = (proxy, method, args) -> "你被代理了 " + method.getName();
return Proxy.newProxyInstance(classLoader, classes, handler);
}
@Override
public Class<?> getObjectType() {
return IUserDao.class;
}
}
- FactoryBean 在 spring 起到著二當家的地位,它將近有70多個小弟(實作它的介面定義),那么它有三個方法;
- T getObject() throws Exception; 回傳bean實體物件
- Class<?> getObjectType(); 回傳實體型別別
- boolean isSingleton(); 判斷是否單例,單例會放到Spring容器中單實體快取池中
- 在這里我們把上面使用Java代理的物件放到了 getObject() 方法中,那么現在再從 Spring 中獲取到的物件,就是我們的代理物件了,
4. Bean 注冊
public class RegisterBeanFactory implements BeanDefinitionRegistryPostProcessor {
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
beanDefinition.setBeanClass(ProxyBeanFactory.class);
BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(beanDefinition, "userDao");
BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, registry);
}
}
在 Spring 的 Bean 管理中,所有的 Bean 最終都會被注冊到類 DefaultListableBeanFactory 中,以上這部分代碼主要的內容包括:
- 實作 BeanDefinitionRegistryPostProcessor.postProcessBeanDefinitionRegistry方法,獲取 Bean 注冊物件,
- 定義 Bean,GenericBeanDefinition,這里主要設定了我們的代理類工廠,
- 創建 Bean 定義處理類,BeanDefinitionHolder,這里需要的主要引數;定義 Bean 和名稱
setBeanClass(ProxyBeanFactory.class), - 最后將我們自己的bean注冊到spring容器中去,registry.registerBeanDefinition()
5. 測驗驗證
在上面我們已經把自定義代理的 Bean 注冊到了 Spring 容器中,接下來我們來測驗下這個代理的 Bean 被如何呼叫,
1. 定義 spring-config.xml
<bean id="userDao" class="org.itstack.interview.bean.RegisterBeanFactory"/>
- 這里我們把 RegisterBeanFactory 配置到 spring 的 xml 配置中,便于啟動時加載,
2. 單元測驗
@Test
public void test_IUserDao() {
BeanFactory beanFactory = new ClassPathXmlApplicationContext("spring-config.xml");
IUserDao userDao = beanFactory.getBean("userDao", IUserDao.class);
String res = userDao.queryUserInfo();
logger.info("測驗結果:{}", res);
}
測驗結果
22:53:14.759 [main] DEBUG o.s.c.e.PropertySourcesPropertyResolver - Could not find key 'spring.liveBeansView.mbeanDomain' in any property source
22:53:14.760 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'userDao'
22:53:14.796 [main] INFO org.itstack.interview.test.ApiTest - 測驗結果:你被代理了 queryUserInfo
Process finished with exit code 0
- 從測驗結果可以看到,我們已經可以通過注入到Spring的代理Bean物件,實作我們的預期結果,
- 其實這個程序也是很多框架中用到的方式,尤其是在一些中間件開發,類似的 ORM 框架都需要使用到,
三、手寫個Mybatis
擴展上一篇原始碼分析工程;itstack-demo-mybatis,增加 like 包,模仿 Mybatis 工程,完整規程下載 https://github.com/fuzhengwei/CodeGuide/wiki
itstack-demo-mybatis
└── src
├── main
│ ├── java
│ │ └── org.itstack.demo
│ │ ├── dao
│ │ │ ├── ISchool.java
│ │ │ └── IUserDao.java
│ │ ├── like
│ │ │ ├── Configuration.java
│ │ │ ├── DefaultSqlSession.java
│ │ │ ├── DefaultSqlSessionFactory.java
│ │ │ ├── Resources.java
│ │ │ ├── SqlSession.java
│ │ │ ├── SqlSessionFactory.java
│ │ │ ├── SqlSessionFactoryBuilder.java
│ │ │ └── SqlSessionFactoryBuilder.java
│ │ └── interfaces
│ │ ├── School.java
│ │ └── User.java
│ ├── resources
│ │ ├── mapper
│ │ │ ├── School_Mapper.xml
│ │ │ └── User_Mapper.xml
│ │ ├── props
│ │ │ └── jdbc.properties
│ │ ├── spring
│ │ │ ├── mybatis-config-datasource.xml
│ │ │ └── spring-config-datasource.xml
│ │ ├── logback.xml
│ │ ├── mybatis-config.xml
│ │ └── spring-config.xml
│ └── webapp
│ └── WEB-INF
└── test
└── java
└── org.itstack.demo.test
├── ApiLikeTest.java
├── MybatisApiTest.java
└── SpringApiTest.java
關于整個 Demo 版本,并不是把所有 Mybatis 全部實作一遍,而是撥絲抽繭將最核心的內容展示給你,從使用上你會感受一模一樣,但是實作類已經全部被替換,核心類包括;
- Configuration
- DefaultSqlSession
- DefaultSqlSessionFactory
- Resources
- SqlSession
- SqlSessionFactory
- SqlSessionFactoryBuilder
- XNode
1. 先測驗下整個DemoJdbc框架
ApiLikeTest.test_queryUserInfoById()
@Test
public void test_queryUserInfoById() {
String resource = "spring/mybatis-config-datasource.xml";
Reader reader;
try {
reader = Resources.getResourceAsReader(resource);
SqlSessionFactory sqlMapper = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = sqlMapper.openSession();
try {
User user = session.selectOne("org.itstack.demo.dao.IUserDao.queryUserInfoById", 1L);
System.out.println(JSON.toJSONString(user));
} finally {
session.close();
reader.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
一切順利結果如下(新人往往會遇到各種問題);
{"age":18,"createTime":1576944000000,"id":1,"name":"水水","updateTime":1576944000000}
Process finished with exit code 0
可能乍一看這測驗類完全和 MybatisApiTest.java 測驗的代碼一模一樣呀,也看不出區別,其實他們的引入的包是不一樣;
MybatisApiTest.java 里面引入的包
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
ApiLikeTest.java 里面引入的包
import org.itstack.demo.like.Resources;
import org.itstack.demo.like.SqlSession;
import org.itstack.demo.like.SqlSessionFactory;
import org.itstack.demo.like.SqlSessionFactoryBuilder;
好!接下來我們開始分析這部分核心代碼,
2. 加載XML組態檔
這里我們采用 mybatis 的組態檔結構進行決議,在不破壞原有結構的情況下,最大可能的貼近原始碼,mybatis 單獨使用的使用的時候使用了兩個組態檔;資料源配置、Mapper 映射配置,如下;
mybatis-config-datasource.xml & 資料源配置
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/itstack?useUnicode=true"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="mapper/User_Mapper.xml"/>
<mapper resource="mapper/School_Mapper.xml"/>
</mappers>
</configuration>
User_Mapper.xml & Mapper 映射配置
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.itstack.demo.dao.IUserDao">
<select id="queryUserInfoById" parameterType="java.lang.Long" resultType="org.itstack.demo.po.User">
SELECT id, name, age, createTime, updateTime
FROM user
where id = #{id}
</select>
<select id="queryUserList" parameterType="org.itstack.demo.po.User" resultType="org.itstack.demo.po.User">
SELECT id, name, age, createTime, updateTime
FROM user
where age = #{age}
</select>
</mapper>
這里的加載程序與 mybaits 不同,我們采用 dom4j 方式,在案例中會看到最開始獲取資源,如下;
ApiLikeTest.test_queryUserInfoById() & 部分截取
String resource = "spring/mybatis-config-datasource.xml";
Reader reader;
try {
reader = Resources.getResourceAsReader(resource);
...
從上可以看到這是通過組態檔地址獲取到了讀取流的程序,從而為后面決議做基礎,首先我們先看 Resources 類,整個是我們的資源類,
Resources.java & 資源類
/**
* 博 客 | https://bugstack.cn
* Create by 小傅哥 @2020
*/
public class Resources {
public static Reader getResourceAsReader(String resource) throws IOException {
return new InputStreamReader(getResourceAsStream(resource));
}
private static InputStream getResourceAsStream(String resource) throws IOException {
ClassLoader[] classLoaders = getClassLoaders();
for (ClassLoader classLoader : classLoaders) {
InputStream inputStream = classLoader.getResourceAsStream(resource);
if (null != inputStream) {
return inputStream;
}
}
throw new IOException("Could not find resource " + resource);
}
private static ClassLoader[] getClassLoaders() {
return new ClassLoader[]{
ClassLoader.getSystemClassLoader(),
Thread.currentThread().getContextClassLoader()};
}
}
這段代碼方法的入口是getResourceAsReader,直到往下以此做了;
- 獲取 ClassLoader 集合,最大限度搜索組態檔
- 通過 classLoader.getResourceAsStream 讀取配置資源,找到后立即回傳,否則拋出例外
3. 決議XML組態檔
組態檔加載后開始進行決議操作,這里我們也仿照 mybatis 但進行簡化,如下;
SqlSessionFactory sqlMapper = new SqlSessionFactoryBuilder().build(reader);
SqlSessionFactoryBuilder.build() & 入口構建類
public DefaultSqlSessionFactory build(Reader reader) {
SAXReader saxReader = new SAXReader();
try {
Document document = saxReader.read(new InputSource(reader));
Configuration configuration = parseConfiguration(document.getRootElement());
return new DefaultSqlSessionFactory(configuration);
} catch (DocumentException e) {
e.printStackTrace();
}
return null;
}
- 通過讀取流創建 xml 決議的 Document 類
- parseConfiguration 進行決議 xml 檔案,并將結果設定到配置類中,包括;連接池、資料源、mapper關系
SqlSessionFactoryBuilder.parseConfiguration() & 決議程序
private Configuration parseConfiguration(Element root) {
Configuration configuration = new Configuration();
configuration.setDataSource(dataSource(root.selectNodes("//dataSource")));
configuration.setConnection(connection(configuration.dataSource));
configuration.setMapperElement(mapperElement(root.selectNodes("mappers")));
return configuration;
}
- 在前面的 xml 內容中可以看到,我們需要決議出資料庫連接池資訊 datasource,還有資料庫陳述句映射關系 mappers
SqlSessionFactoryBuilder.dataSource() & 決議出資料源
private Map<String, String> dataSource(List<Element> list) {
Map<String, String> dataSource = new HashMap<>(4);
Element element = list.get(0);
List content = element.content();
for (Object o : content) {
Element e = (Element) o;
String name = e.attributeValue("name");
String value = e.attributeValue("value");
dataSource.put(name, value);
}
return dataSource;
}
- 這個程序比較簡單,只需要將資料源資訊獲取即可
SqlSessionFactoryBuilder.connection() & 獲取資料庫連接
private Connection connection(Map<String, String> dataSource) {
try {
Class.forName(dataSource.get("driver"));
return DriverManager.getConnection(dataSource.get("url"), dataSource.get("username"), dataSource.get("password"));
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
return null;
}
- 這個就是jdbc最原始的代碼,獲取了資料庫連接池
SqlSessionFactoryBuilder.mapperElement() & 決議SQL陳述句
private Map<String, XNode> mapperElement(List<Element> list) {
Map<String, XNode> map = new HashMap<>();
Element element = list.get(0);
List content = element.content();
for (Object o : content) {
Element e = (Element) o;
String resource = e.attributeValue("resource");
try {
Reader reader = Resources.getResourceAsReader(resource);
SAXReader saxReader = new SAXReader();
Document document = saxReader.read(new InputSource(reader));
Element root = document.getRootElement();
//命名空間
String namespace = root.attributeValue("namespace");
// SELECT
List<Element> selectNodes = root.selectNodes("select");
for (Element node : selectNodes) {
String id = node.attributeValue("id");
String parameterType = node.attributeValue("parameterType");
String resultType = node.attributeValue("resultType");
String sql = node.getText();
// ? 匹配
Map<Integer, String> parameter = new HashMap<>();
Pattern pattern = Pattern.compile("(#\\{(.*?)})");
Matcher matcher = pattern.matcher(sql);
for (int i = 1; matcher.find(); i++) {
String g1 = matcher.group(1);
String g2 = matcher.group(2);
parameter.put(i, g2);
sql = sql.replace(g1, "?");
}
XNode xNode = new XNode();
xNode.setNamespace(namespace);
xNode.setId(id);
xNode.setParameterType(parameterType);
xNode.setResultType(resultType);
xNode.setSql(sql);
xNode.setParameter(parameter);
map.put(namespace + "." + id, xNode);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
return map;
}
- 這個程序首先包括是決議所有的sql陳述句,目前為了測驗只決議 select 相關
- 所有的 sql 陳述句為了確認唯一,都是使用;namespace + select中的id進行拼接,作為 key,之后與sql一起存放到 map 中,
- 在 mybaits 的 sql 陳述句配置中,都有占位符,用于傳參,where id = #{id} 所以我們需要將占位符設定為問號,另外需要將占位符的順序資訊與名稱存放到 map 結構,方便后續設定查詢時候的入參,
4. 創建DefaultSqlSessionFactory
最后將初始化后的配置類 Configuration,作為引數進行創建 DefaultSqlSessionFactory,如下;
public DefaultSqlSessionFactory build(Reader reader) {
SAXReader saxReader = new SAXReader();
try {
Document document = saxReader.read(new InputSource(reader));
Configuration configuration = parseConfiguration(document.getRootElement());
return new DefaultSqlSessionFactory(configuration);
} catch (DocumentException e) {
e.printStackTrace();
}
return null;
}
DefaultSqlSessionFactory.java & SqlSessionFactory的實作類
public class DefaultSqlSessionFactory implements SqlSessionFactory {
private final Configuration configuration;
public DefaultSqlSessionFactory(Configuration configuration) {
this.configuration = configuration;
}
@Override
public SqlSession openSession() {
return new DefaultSqlSession(configuration.connection, configuration.mapperElement);
}
}
- 這個程序比較簡單,建構式只提供了配置類入參
- 實作 SqlSessionFactory 的 openSession(),用于創建 DefaultSqlSession,也就可以執行 sql 操作
5. 開啟SqlSession
SqlSession session = sqlMapper.openSession();
上面這一步就是創建了DefaultSqlSession,比較簡單,如下;
@Override
public SqlSession openSession() {
return new DefaultSqlSession(configuration.connection, configuration.mapperElement);
}
6. 執行SQL陳述句
User user = session.selectOne("org.itstack.demo.dao.IUserDao.queryUserInfoById", 1L);
在 DefaultSqlSession 中通過實作 SqlSession,提供資料庫陳述句查詢和關閉連接池,如下;
SqlSession.java & 定義
public interface SqlSession {
<T> T selectOne(String statement);
<T> T selectOne(String statement, Object parameter);
<T> List<T> selectList(String statement);
<T> List<T> selectList(String statement, Object parameter);
void close();
}
接下來看具體的執行程序,session.selectOne
DefaultSqlSession.selectOne() & 執行查詢
public <T> T selectOne(String statement, Object parameter) {
XNode xNode = mapperElement.get(statement);
Map<Integer, String> parameterMap = xNode.getParameter();
try {
PreparedStatement preparedStatement = connection.prepareStatement(xNode.getSql());
buildParameter(preparedStatement, parameter, parameterMap);
ResultSet resultSet = preparedStatement.executeQuery();
List<T> objects = resultSet2Obj(resultSet, Class.forName(xNode.getResultType()));
return objects.get(0);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
-
selectOne 就objects.get(0);,selectList 就全部回傳
-
通過 statement 獲取最初決議 xml 時候的存盤的 select 標簽資訊;
<select id="queryUserInfoById" parameterType="java.lang.Long" resultType="org.itstack.demo.po.User"> SELECT id, name, age, createTime, updateTime FROM user where id = #{id} </select> -
獲取 sql 陳述句后交給 jdbc 的 PreparedStatement 類進行執行
-
這里還需要設定入參,我們將入參設定進行抽取,如下;
private void buildParameter(PreparedStatement preparedStatement, Object parameter, Map<Integer, String> parameterMap) throws SQLException, IllegalAccessException { int size = parameterMap.size(); // 單個引數 if (parameter instanceof Long) { for (int i = 1; i <= size; i++) { preparedStatement.setLong(i, Long.parseLong(parameter.toString())); } return; } if (parameter instanceof Integer) { for (int i = 1; i <= size; i++) { preparedStatement.setInt(i, Integer.parseInt(parameter.toString())); } return; } if (parameter instanceof String) { for (int i = 1; i <= size; i++) { preparedStatement.setString(i, parameter.toString()); } return; } Map<String, Object> fieldMap = new HashMap<>(); // 物件引數 Field[] declaredFields = parameter.getClass().getDeclaredFields(); for (Field field : declaredFields) { String name = field.getName(); field.setAccessible(true); Object obj = field.get(parameter); field.setAccessible(false); fieldMap.put(name, obj); } for (int i = 1; i <= size; i++) { String parameterDefine = parameterMap.get(i); Object obj = fieldMap.get(parameterDefine); if (obj instanceof Short) { preparedStatement.setShort(i, Short.parseShort(obj.toString())); continue; } if (obj instanceof Integer) { preparedStatement.setInt(i, Integer.parseInt(obj.toString())); continue; } if (obj instanceof Long) { preparedStatement.setLong(i, Long.parseLong(obj.toString())); continue; } if (obj instanceof String) { preparedStatement.setString(i, obj.toString()); continue; } if (obj instanceof Date) { preparedStatement.setDate(i, (java.sql.Date) obj); } } }- 單個引數比較簡單直接設定值即可,Long、Integer、String …
- 如果是一個類物件,需要通過獲取 Field 屬性,與引數 Map 進行匹配設定
-
設定引數后執行查詢 preparedStatement.executeQuery()
-
接下來需要將查詢結果轉換為我們的類(主要是反射類的操作),resultSet2Obj(resultSet, Class.forName(xNode.getResultType()));
private <T> List<T> resultSet2Obj(ResultSet resultSet, Class<?> clazz) { List<T> list = new ArrayList<>(); try { ResultSetMetaData metaData = resultSet.getMetaData(); int columnCount = metaData.getColumnCount(); // 每次遍歷行值 while (resultSet.next()) { T obj = (T) clazz.newInstance(); for (int i = 1; i <= columnCount; i++) { Object value = resultSet.getObject(i); String columnName = metaData.getColumnName(i); String setMethod = "set" + columnName.substring(0, 1).toUpperCase() + columnName.substring(1); Method method; if (value instanceof Timestamp) { method = clazz.getMethod(setMethod, Date.class); } else { method = clazz.getMethod(setMethod, value.getClass()); } method.invoke(obj, value); } list.add(obj); } } catch (Exception e) { e.printStackTrace(); } return list; }- 主要通過反射生成我們的類物件,這個類的型別定義在 sql 標簽上
- 時間型別需要判斷后處理,Timestamp,與 java 不是一個型別
7. Sql查詢補充說明
sql 查詢有入參、有不需要入參、有查詢一個、有查詢集合,只需要合理包裝即可,例如下面的查詢集合,入參是物件型別;
ApiLikeTest.test_queryUserList()
@Test
public void test_queryUserList() {
String resource = "spring/mybatis-config-datasource.xml";
Reader reader;
try {
reader = Resources.getResourceAsReader(resource);
SqlSessionFactory sqlMapper = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = sqlMapper.openSession();
try {
User req = new User();
req.setAge(18);
List<User> userList = session.selectList("org.itstack.demo.dao.IUserDao.queryUserList", req);
System.out.println(JSON.toJSONString(userList));
} finally {
session.close();
reader.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
**測驗結果:
[{"age":18,"createTime":1576944000000,"id":1,"name":"水水","updateTime":1576944000000},{"age":18,"createTime":1576944000000,"id":2,"name":"豆豆","updateTime":1576944000000}]
Process finished with exit code 0
四、原始碼分析(mybatis)
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
Mybatis的整個原始碼還是很大的,以下主要將部分核心內容進行整理分析,以便于后續分析Mybatis與Spring整合的原始碼部分,簡要包括;容器初始化、組態檔決議、Mapper加載與動態代理,
1. 從一個簡單的案例開始
要學習Mybatis原始碼,最好的方式一定是從一個簡單的點進入,而不是從Spring整合開始分析,SqlSessionFactory是整個Mybatis的核心實體物件,SqlSessionFactory物件的實體又通過SqlSessionFactoryBuilder物件來獲得,SqlSessionFactoryBuilder物件可以從XML組態檔加載配置資訊,然后創建SqlSessionFactory,如下例子:
MybatisApiTest.java
public class MybatisApiTest {
@Test
public void test_queryUserInfoById() {
String resource = "spring/mybatis-config-datasource.xml";
Reader reader;
try {
reader = Resources.getResourceAsReader(resource);
SqlSessionFactory sqlMapper = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = sqlMapper.openSession();
try {
User user = session.selectOne("org.itstack.demo.dao.IUserDao.queryUserInfoById", 1L);
System.out.println(JSON.toJSONString(user));
} finally {
session.close();
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
dao/IUserDao.java
public interface IUserDao {
User queryUserInfoById(Long id);
}
spring/mybatis-config-datasource.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/itstack?useUnicode=true"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="mapper/User_Mapper.xml"/>
</mappers>
</configuration>
如果一切順利,那么會有如下結果:
{"age":18,"createTime":1571376957000,"id":1,"name":"花花","updateTime":1571376957000}
從上面的代碼塊可以看到,核心代碼;SqlSessionFactoryBuilder().build(reader),負責Mybatis組態檔的加載、決議、構建等職責,直到最終可以通過SqlSession來執行并回傳結果,
2. 容器初始化
從上面代碼可以看到,SqlSessionFactory是通過SqlSessionFactoryBuilder工廠類創建的,而不是直接使用構造器,容器的組態檔加載和初始化流程如下:

- 流程核心類
- SqlSessionFactoryBuilder
- XMLConfigBuilder
- XPathParser
- Configuration
SqlSessionFactoryBuilder.java
public class SqlSessionFactoryBuilder {
public SqlSessionFactory build(Reader reader) {
return build(reader, null, null);
}
public SqlSessionFactory build(Reader reader, String environment) {
return build(reader, environment, null);
}
public SqlSessionFactory build(Reader reader, Properties properties) {
return build(reader, null, properties);
}
public SqlSessionFactory build(Reader reader, String environment, Properties properties) {
try {
XMLConfigBuilder parser = new XMLConfigBuilder(reader, environment, properties);
return build(parser.parse());
} catch (Exception e) {
throw ExceptionFactory.wrapException("Error building SqlSession.", e);
} finally {
ErrorContext.instance().reset();
try {
reader.close();
} catch (IOException e) {
// Intentionally ignore. Prefer previous error.
}
}
}
public SqlSessionFactory build(InputStream inputStream) {
return build(inputStream, null, null);
}
public SqlSessionFactory build(InputStream inputStream, String environment) {
return build(inputStream, environment, null);
}
public SqlSessionFactory build(InputStream inputStream, Properties properties) {
return build(inputStream, null, properties);
}
public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) {
try {
XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties);
return build(parser.parse());
} catch (Exception e) {
throw ExceptionFactory.wrapException("Error building SqlSession.", e);
} finally {
ErrorContext.instance().reset();
try {
inputStream.close();
} catch (IOException e) {
// Intentionally ignore. Prefer previous error.
}
}
}
public SqlSessionFactory build(Configuration config) {
return new DefaultSqlSessionFactory(config);
}
}
從上面的原始碼可以看到,SqlSessionFactory提供三種方式build構建物件;
- 位元組流:java.io.InputStream
- 字符流:java.io.Reader
- 配置類:org.apache.ibatis.session.Configuration
那么,位元組流、字符流都會創建組態檔決議類:XMLConfigBuilder,并通過parser.parse()生成Configuration,最后呼叫配置類構建方法生成SqlSessionFactory,
XMLConfigBuilder.java
public class XMLConfigBuilder extends BaseBuilder {
private boolean parsed;
private final XPathParser parser;
private String environment;
private final ReflectorFactory localReflectorFactory = new DefaultReflectorFactory();
...
public XMLConfigBuilder(Reader reader, String environment, Properties props) {
this(new XPathParser(reader, true, props, new XMLMapperEntityResolver()), environment, props);
}
...
}
- XMLConfigBuilder對于XML檔案的加載和決議都委托于XPathParser,最終使用JDK自帶的javax.xml進行XML決議(XPath)
- XPathParser(Reader reader, boolean validation, Properties variables, EntityResolver entityResolver)
- reader:使用字符流創建新的輸入源,用于對XML檔案的讀取
- validation:是否進行DTD校驗
- variables:屬性配置資訊
- entityResolver:Mybatis硬編碼了new XMLMapperEntityResolver()提供XML默認決議器
XMLMapperEntityResolver.java
public class XMLMapperEntityResolver implements EntityResolver {
private static final String IBATIS_CONFIG_SYSTEM = "ibatis-3-config.dtd";
private static final String IBATIS_MAPPER_SYSTEM = "ibatis-3-mapper.dtd";
private static final String MYBATIS_CONFIG_SYSTEM = "mybatis-3-config.dtd";
private static final String MYBATIS_MAPPER_SYSTEM = "mybatis-3-mapper.dtd";
private static final String MYBATIS_CONFIG_DTD = "org/apache/ibatis/builder/xml/mybatis-3-config.dtd";
private static final String MYBATIS_MAPPER_DTD = "org/apache/ibatis/builder/xml/mybatis-3-mapper.dtd";
/*
* Converts a public DTD into a local one
*
* @param publicId The public id that is what comes after "PUBLIC"
* @param systemId The system id that is what comes after the public id.
* @return The InputSource for the DTD
*
* @throws org.xml.sax.SAXException If anything goes wrong
*/
@Override
public InputSource resolveEntity(String publicId, String systemId) throws SAXException {
try {
if (systemId != null) {
String lowerCaseSystemId = systemId.toLowerCase(Locale.ENGLISH);
if (lowerCaseSystemId.contains(MYBATIS_CONFIG_SYSTEM) || lowerCaseSystemId.contains(IBATIS_CONFIG_SYSTEM)) {
return getInputSource(MYBATIS_CONFIG_DTD, publicId, systemId);
} else if (lowerCaseSystemId.contains(MYBATIS_MAPPER_SYSTEM) || lowerCaseSystemId.contains(IBATIS_MAPPER_SYSTEM)) {
return getInputSource(MYBATIS_MAPPER_DTD, publicId, systemId);
}
}
return null;
} catch (Exception e) {
throw new SAXException(e.toString());
}
}
private InputSource getInputSource(String path, String publicId, String systemId) {
InputSource source = null;
if (path != null) {
try {
InputStream in = Resources.getResourceAsStream(path);
source = new InputSource(in);
source.setPublicId(publicId);
source.setSystemId(systemId);
} catch (IOException e) {
// ignore, null is ok
}
}
return source;
}
}
- Mybatis依賴于dtd檔案進行進行決議,其中的ibatis-3-config.dtd主要是用于兼容用途
- getInputSource(String path, String publicId, String systemId)的呼叫里面有兩個引數publicId(公共識別符號)和systemId(系統標示符)
XPathParser.java
public XPathParser(Reader reader, boolean validation, Properties variables, EntityResolver entityResolver) {
commonConstructor(validation, variables, entityResolver);
this.document = createDocument(new InputSource(reader));
}
private void commonConstructor(boolean validation, Properties variables, EntityResolver entityResolver) {
this.validation = validation;
this.entityResolver = entityResolver;
this.variables = variables;
XPathFactory factory = XPathFactory.newInstance();
this.xpath = factory.newXPath();
}
private Document createDocument(InputSource inputSource) {
// important: this must only be called AFTER common constructor
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(validation);
factory.setNamespaceAware(false);
factory.setIgnoringComments(true);
factory.setIgnoringElementContentWhitespace(false);
factory.setCoalescing(false);
factory.setExpandEntityReferences(true);
DocumentBuilder builder = factory.newDocumentBuilder();
builder.setEntityResolver(entityResolver);
builder.setErrorHandler(new ErrorHandler() {
@Override
public void error(SAXParseException exception) throws SAXException {
throw exception;
}
@Override
public void fatalError(SAXParseException exception) throws SAXException {
throw exception;
}
@Override
public void warning(SAXParseException exception) throws SAXException {
}
});
return builder.parse(inputSource);
} catch (Exception e) {
throw new BuilderException("Error creating document instance. Cause: " + e, e);
}
}
-
從上到下可以看到主要是為了創建一個Mybatis的檔案決議器,最后根據builder.parse(inputSource)回傳Document
-
得到XPathParser實體后,接下來在呼叫方法:this(new XPathParser(reader, true, props, new XMLMapperEntityResolver()), environment, props);
XMLConfigBuilder.this(new XPathParser(reader, true, props, new XMLMapperEntityResolver()), environment, props); private XMLConfigBuilder(XPathParser parser, String environment, Properties props) { super(new Configuration()); ErrorContext.instance().resource("SQL Mapper Configuration"); this.configuration.setVariables(props); this.parsed = false; this.environment = environment; this.parser = parser; } -
其中呼叫了父類的建構式
public abstract class BaseBuilder { protected final Configuration configuration; protected final TypeAliasRegistry typeAliasRegistry; protected final TypeHandlerRegistry typeHandlerRegistry; public BaseBuilder(Configuration configuration) { this.configuration = configuration; this.typeAliasRegistry = this.configuration.getTypeAliasRegistry(); this.typeHandlerRegistry = this.configuration.getTypeHandlerRegistry(); } } -
XMLConfigBuilder創建完成后,sqlSessionFactoryBuild呼叫parser.parse()創建Configuration
public class XMLConfigBuilder extends BaseBuilder { public Configuration parse() { if (parsed) { throw new BuilderException("Each XMLConfigBuilder can only be used once."); } parsed = true; parseConfiguration(parser.evalNode("/configuration")); return configuration; } }
3. 組態檔決議
這一部分是整個XML檔案決議和裝載的核心內容,其中包括;
- 屬性決議propertiesElement
- 加載settings節點settingsAsProperties
- 載自定義VFS loadCustomVfs
- 決議型別別名typeAliasesElement
- 加載插件pluginElement
- 加載物件工廠objectFactoryElement
- 創建物件包裝器工廠objectWrapperFactoryElement
- 加載反射工廠reflectorFactoryElement
- 元素設定settingsElement
- 加載環境配置environmentsElement
- 資料庫廠商標識加載databaseIdProviderElement
- 加載型別處理器typeHandlerElement
- (核心)加載mapper檔案mapperElement
parseConfiguration(parser.evalNode("/configuration"));
private void parseConfiguration(XNode root) {
try {
//issue #117 read properties first
//屬性決議propertiesElement
propertiesElement(root.evalNode("properties"));
//加載settings節點settingsAsProperties
Properties settings = settingsAsProperties(root.evalNode("settings"));
//加載自定義VFS loadCustomVfs
loadCustomVfs(settings);
//決議型別別名typeAliasesElement
typeAliasesElement(root.evalNode("typeAliases"));
//加載插件pluginElement
pluginElement(root.evalNode("plugins"));
//加載物件工廠objectFactoryElement
objectFactoryElement(root.evalNode("objectFactory"));
//創建物件包裝器工廠objectWrapperFactoryElement
objectWrapperFactoryElement(root.evalNode("objectWrapperFactory"));
//加載反射工廠reflectorFactoryElement
reflectorFactoryElement(root.evalNode("reflectorFactory"));
//元素設定
settingsElement(settings);
// read it after objectFactory and objectWrapperFactory issue #631
//加載環境配置environmentsElement
environmentsElement(root.evalNode("environments"));
//資料庫廠商標識加載databaseIdProviderElement
databaseIdProviderElement(root.evalNode("databaseIdProvider"));
//加載型別處理器typeHandlerElement
typeHandlerElement(root.evalNode("typeHandlers"));
//加載mapper檔案mapperElement
mapperElement(root.evalNode("mappers"));
} catch (Exception e) {
throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);
}
}
所有的root.evalNode()底層都是呼叫XML DOM方法:Object evaluate(String expression, Object item, QName returnType),運算式引數expression,通過XObject resultObject = eval( expression, item )回傳最終節點內容,可以參考http://mybatis.org/dtd/mybatis-3-config.dtd,如下;
<!ELEMENT configuration (properties?, settings?, typeAliases?, typeHandlers?, objectFactory?, objectWrapperFactory?, reflectorFactory?, plugins?, environments?, databaseIdProvider?, mappers?)>
<!ELEMENT databaseIdProvider (property*)>
<!ATTLIST databaseIdProvider
type CDATA #REQUIRED
>
<!ELEMENT properties (property*)>
<!ATTLIST properties
resource CDATA #IMPLIED
url CDATA #IMPLIED
>
<!ELEMENT property EMPTY>
<!ATTLIST property
name CDATA #REQUIRED
value CDATA #REQUIRED
>
<!ELEMENT settings (setting+)>
<!ELEMENT setting EMPTY>
<!ATTLIST setting
name CDATA #REQUIRED
value CDATA #REQUIRED
>
<!ELEMENT typeAliases (typeAlias*,package*)>
<!ELEMENT typeAlias EMPTY>
<!ATTLIST typeAlias
type CDATA #REQUIRED
alias CDATA #IMPLIED
>
<!ELEMENT typeHandlers (typeHandler*,package*)>
<!ELEMENT typeHandler EMPTY>
<!ATTLIST typeHandler
javaType CDATA #IMPLIED
jdbcType CDATA #IMPLIED
handler CDATA #REQUIRED
>
<!ELEMENT objectFactory (property*)>
<!ATTLIST objectFactory
type CDATA #REQUIRED
>
<!ELEMENT objectWrapperFactory EMPTY>
<!ATTLIST objectWrapperFactory
type CDATA #REQUIRED
>
<!ELEMENT reflectorFactory EMPTY>
<!ATTLIST reflectorFactory
type CDATA #REQUIRED
>
<!ELEMENT plugins (plugin+)>
<!ELEMENT plugin (property*)>
<!ATTLIST plugin
interceptor CDATA #REQUIRED
>
<!ELEMENT environments (environment+)>
<!ATTLIST environments
default CDATA #REQUIRED
>
<!ELEMENT environment (transactionManager,dataSource)>
<!ATTLIST environment
id CDATA #REQUIRED
>
<!ELEMENT transactionManager (property*)>
<!ATTLIST transactionManager
type CDATA #REQUIRED
>
<!ELEMENT dataSource (property*)>
<!ATTLIST dataSource
type CDATA #REQUIRED
>
<!ELEMENT mappers (mapper*,package*)>
<!ELEMENT mapper EMPTY>
<!ATTLIST mapper
resource CDATA #IMPLIED
url CDATA #IMPLIED
class CDATA #IMPLIED
>
<!ELEMENT package EMPTY>
<!ATTLIST package
name CDATA #REQUIRED
>
mybatis-3-config.dtd 定義檔案中有11個組態檔,如下;
- properties?,
- settings?,
- typeAliases?,
- typeHandlers?,
- objectFactory?,
- objectWrapperFactory?,
- reflectorFactory?,
- plugins?,
- environments?,
- databaseIdProvider?,
- mappers?
以上每個配置都是可選,最終配置內容會保存到org.apache.ibatis.session.Configuration,如下;
public class Configuration {
protected Environment environment;
// 允許在嵌套陳述句中使用分頁(RowBounds),如果允許使用則設定為false,默認為false
protected boolean safeRowBoundsEnabled;
// 允許在嵌套陳述句中使用分頁(ResultHandler),如果允許使用則設定為false,
protected boolean safeResultHandlerEnabled = true;
// 是否開啟自動駝峰命名規則(camel case)映射,即從經典資料庫列名 A_COLUMN 到經典 Java 屬性名 aColumn 的類似映射,默認false
protected boolean mapUnderscoreToCamelCase;
// 當開啟時,任何方法的呼叫都會加載該物件的所有屬性,否則,每個屬性會按需加載,默認值false (true in ≤3.4.1)
protected boolean aggressiveLazyLoading;
// 是否允許單一陳述句回傳多結果集(需要兼容驅動),
protected boolean multipleResultSetsEnabled = true;
// 允許 JDBC 支持自動生成主鍵,需要驅動兼容,這就是insert時獲取mysql自增主鍵/oracle sequence的開關,注:一般來說,這是希望的結果,應該默認值為true比較合適,
protected boolean useGeneratedKeys;
// 使用列標簽代替列名,一般來說,這是希望的結果
protected boolean useColumnLabel = true;
// 是否啟用快取 {默認是開啟的,可能這也是你的面試題}
protected boolean cacheEnabled = true;
// 指定當結果集中值為 null 的時候是否呼叫映射物件的 setter(map 物件時為 put)方法,這對于有 Map.keySet() 依賴或 null 值初始化的時候是有用的,
protected boolean callSettersOnNulls;
// 允許使用方法簽名中的名稱作為陳述句引數名稱, 為了使用該特性,你的工程必須采用Java 8編譯,并且加上-parameters選項,(從3.4.1開始)
protected boolean useActualParamName = true;
//當回傳行的所有列都是空時,MyBatis默認回傳null, 當開啟這個設定時,MyBatis會回傳一個空實體, 請注意,它也適用于嵌套的結果集 (i.e. collectioin and association),(從3.4.2開始) 注:這里應該拆分為兩個引數比較合適, 一個用于結果集,一個用于單記錄,通常來說,我們會希望結果集不是null,單記錄仍然是null
protected boolean returnInstanceForEmptyRow;
// 指定 MyBatis 增加到日志名稱的前綴,
protected String logPrefix;
// 指定 MyBatis 所用日志的具體實作,未指定時將自動查找,一般建議指定為slf4j或log4j
protected Class <? extends Log> logImpl;
// 指定VFS的實作, VFS是mybatis提供的用于訪問AS內資源的一個簡便介面
protected Class <? extends VFS> vfsImpl;
// MyBatis 利用本地快取機制(Local Cache)防止回圈參考(circular references)和加速重復嵌套查詢, 默認值為 SESSION,這種情況下會快取一個會話中執行的所有查詢, 若設定值為 STATEMENT,本地會話僅用在陳述句執行上,對相同 SqlSession 的不同呼叫將不會共享資料,
protected LocalCacheScope localCacheScope = LocalCacheScope.SESSION;
// 當沒有為引數提供特定的 JDBC 型別時,為空值指定 JDBC 型別, 某些驅動需要指定列的 JDBC 型別,多數情況直接用一般型別即可,比如 NULL、VARCHAR 或 OTHER,
protected JdbcType jdbcTypeForNull = JdbcType.OTHER;
// 指定物件的哪個方法觸發一次延遲加載,
protected Set<String> lazyLoadTriggerMethods = new HashSet<String>(Arrays.asList(new String[] { "equals", "clone", "hashCode", "toString" }));
// 設定超時時間,它決定驅動等待資料庫回應的秒數,默認不超時
protected Integer defaultStatementTimeout;
// 為驅動的結果集設定默認獲取數量,
protected Integer defaultFetchSize;
// SIMPLE 就是普通的執行器;REUSE 執行器會重用預處理陳述句(prepared statements); BATCH 執行器將重用陳述句并執行批量更新,
protected ExecutorType defaultExecutorType = ExecutorType.SIMPLE;
// 指定 MyBatis 應如何自動映射列到欄位或屬性, NONE 表示取消自動映射;PARTIAL 只會自動映射沒有定義嵌套結果集映射的結果集, FULL 會自動映射任意復雜的結果集(無論是否嵌套),
protected AutoMappingBehavior autoMappingBehavior = AutoMappingBehavior.PARTIAL;
// 指定發現自動映射目標未知列(或者未知屬性型別)的行為,這個值應該設定為WARNING比較合適
protected AutoMappingUnknownColumnBehavior autoMappingUnknownColumnBehavior = AutoMappingUnknownColumnBehavior.NONE;
// settings下的properties屬性
protected Properties variables = new Properties();
// 默認的反射器工廠,用于操作屬性、構造器方便
protected ReflectorFactory reflectorFactory = new DefaultReflectorFactory();
// 物件工廠, 所有的類resultMap類都需要依賴于物件工廠來實體化
protected ObjectFactory objectFactory = new DefaultObjectFactory();
// 物件包裝器工廠,主要用來在創建非原生物件,比如增加了某些監控或者特殊屬性的代理類
protected ObjectWrapperFactory objectWrapperFactory = new DefaultObjectWrapperFactory();
// 延遲加載的全域開關,當開啟時,所有關聯物件都會延遲加載,特定關聯關系中可通過設定fetchType屬性來覆寫該項的開關狀態,
protected boolean lazyLoadingEnabled = false;
// 指定 Mybatis 創建具有延遲加載能力的物件所用到的代理工具,MyBatis 3.3+使用JAVASSIST
protected ProxyFactory proxyFactory = new JavassistProxyFactory(); // #224 Using internal Javassist instead of OGNL
// MyBatis 可以根據不同的資料庫廠商執行不同的陳述句,這種多廠商的支持是基于映射陳述句中的 databaseId 屬性,
protected String databaseId;
...
}
以上可以看到,Mybatis把所有的配置;resultMap、Sql陳述句、插件、快取等都維護在Configuration中,這里還有一個小技巧,在Configuration還有一個StrictMap內部類,它繼承于HashMap完善了put時防重、get時取不到值的例外處理,如下;
protected static class StrictMap<V> extends HashMap<String, V> {
private static final long serialVersionUID = -4950446264854982944L;
private final String name;
public StrictMap(String name, int initialCapacity, float loadFactor) {
super(initialCapacity, loadFactor);
this.name = name;
}
public StrictMap(String name, int initialCapacity) {
super(initialCapacity);
this.name = name;
}
public StrictMap(String name) {
super();
this.name = name;
}
public StrictMap(String name, Map<String, ? extends V> m) {
super(m);
this.name = name;
}
}
(核心)加載mapper檔案mapperElement
Mapper檔案處理是Mybatis框架的核心服務,所有的SQL陳述句都撰寫在Mapper中,這塊也是我們分析的重點,其他模塊可以后續講解,
XMLConfigBuilder.parseConfiguration()->mapperElement(root.evalNode(“mappers”));
private void mapperElement(XNode parent) throws Exception {
if (parent != null) {
for (XNode child : parent.getChildren()) {
// 如果要同時使用package自動掃描和通過mapper明確指定要加載的mapper,一定要確保package自動掃描的范圍不包含明確指定的mapper,否則在通過package掃描的interface的時候,嘗試加載對應xml檔案的loadXmlResource()的邏輯中出現判重出錯,報org.apache.ibatis.binding.BindingException例外,即使xml檔案中包含的內容和mapper介面中包含的陳述句不重復也會出錯,包括加載mapper介面時自動加載的xml mapper也一樣會出錯,
if ("package".equals(child.getName())) {
String mapperPackage = child.getStringAttribute("name");
configuration.addMappers(mapperPackage);
} else {
String resource = child.getStringAttribute("resource");
String url = child.getStringAttribute("url");
String mapperClass = child.getStringAttribute("class");
if (resource != null && url == null && mapperClass == null) {
ErrorContext.instance().resource(resource);
InputStream inputStream = Resources.getResourceAsStream(resource);
XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, resource, configuration.getSqlFragments());
mapperParser.parse();
} else if (resource == null && url != null && mapperClass == null) {
ErrorContext.instance().resource(url);
InputStream inputStream = Resources.getUrlAsStream(url);
XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, url, configuration.getSqlFragments());
mapperParser.parse();
} else if (resource == null && url == null && mapperClass != null) {
Class<?> mapperInterface = Resources.classForName(mapperClass);
configuration.addMapper(mapperInterface);
} else {
throw new BuilderException("A mapper element may only specify a url, resource or class, but not more than one.");
}
}
}
}
}
-
Mybatis提供了兩類配置Mapper的方法,第一類是使用package自動搜索的模式,這樣指定package下所有介面都會被注冊為mapper,也是在Spring中比較常用的方式,例如:
<mappers> <package name="org.itstack.demo"/> </mappers> -
另外一類是明確指定Mapper,這又可以通過resource、url或者class進行細分,例如;
<mappers> <mapper resource="mapper/User_Mapper.xml"/> <mapper class=""/> <mapper url=""/> </mappers>
4. Mapper加載與動態代理
通過package方式自動搜索加載,生成對應的mapper代理類,代碼塊和流程,如下;
private void mapperElement(XNode parent) throws Exception {
if (parent != null) {
for (XNode child : parent.getChildren()) {
if ("package".equals(child.getName())) {
String mapperPackage = child.getStringAttribute("name");
configuration.addMappers(mapperPackage);
} else {
...
}
}
}
}

Mapper加載到生成代理物件的流程中,主要的核心類包括;
- XMLConfigBuilder
- Configuration
- MapperRegistry
- MapperAnnotationBuilder
- MapperProxyFactory
MapperRegistry.java
決議加載Mapper
public void addMappers(String packageName, Class<?> superType) {
// mybatis框架提供的搜索classpath下指定package以及子package中符合條件(注解或者繼承于某個類/介面)的類,默認使用Thread.currentThread().getContextClassLoader()回傳的加載器,和spring的工具類殊途同歸,
ResolverUtil<Class<?>> resolverUtil = new ResolverUtil<Class<?>>();
// 無條件的加載所有的類,因為呼叫方傳遞了Object.class作為父類,這也給以后的指定mapper介面預留了余地
resolverUtil.find(new ResolverUtil.IsA(superType), packageName);
// 所有匹配的calss都被存盤在ResolverUtil.matches欄位中
Set<Class<? extends Class<?>>> mapperSet = resolverUtil.getClasses();
for (Class<?> mapperClass : mapperSet) {
//呼叫addMapper方法進行具體的mapper類/介面決議
addMapper(mapperClass);
}
}
生成代理類:MapperProxyFactory
public <T> void addMapper(Class<T> type) {
// 對于mybatis mapper介面檔案,必須是interface,不能是class
if (type.isInterface()) {
if (hasMapper(type)) {
throw new 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.
MapperAnnotationBuilder parser = new MapperAnnotationBuilder(config, type);
parser.parse();
loadCompleted = true;
} finally {
if (!loadCompleted) {
knownMappers.remove(type);
}
}
}
}
在MapperRegistry中維護了介面類與代理工程的映射關系,knownMappers;
private final Map<Class<?>, MapperProxyFactory<?>> knownMappers = new HashMap<Class<?>, MapperProxyFactory<?>>();
MapperProxyFactory.java
public class MapperProxyFactory<T> {
private final Class<T> mapperInterface;
private final Map<Method, MapperMethod> methodCache = new ConcurrentHashMap<Method, MapperMethod>();
public MapperProxyFactory(Class<T> mapperInterface) {
this.mapperInterface = mapperInterface;
}
public Class<T> getMapperInterface() {
return mapperInterface;
}
public Map<Method, MapperMethod> getMethodCache() {
return methodCache;
}
@SuppressWarnings("unchecked")
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);
}
}
如上是Mapper的代理類工程,建構式中的mapperInterface就是對應的介面類,當實體化時候會獲得具體的MapperProxy代理,里面主要包含了SqlSession,
五、原始碼分析(mybatis-spring)
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.2</version>
</dependency>
作為一款好用的ORM框架,一定是蘿莉臉(單純)、御姐心(強大),鋪的了床(屏蔽與JDBC直接打交道)、暖的了房(速度性能好)!鑒于這些優點幾乎在國內互聯網大部分開發框架都會使用到Mybatis,尤其在一些需要高性能的場景下需要優化sql那么一定需要手寫sql在xml中,那么,準備好了嗎!開始分析分析它的原始碼;
1. 從一個簡單的案例開始
與分析mybatis原始碼一樣,先做一個簡單的案例;定義dao、撰寫組態檔、junit單元測驗;
SpringApiTest.java
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:spring-config.xml")
public class SpringApiTest {
private Logger logger = LoggerFactory.getLogger(SpringApiTest.class);
@Resource
private ISchoolDao schoolDao;
@Resource
private IUserDao userDao;
@Test
public void test_queryRuleTreeByTreeId(){
School ruleTree = schoolDao.querySchoolInfoById(1L);
logger.info(JSON.toJSONString(ruleTree));
User user = userDao.queryUserInfoById(1L);
logger.info(JSON.toJSONString(user));
}
}
spring-config-datasource.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 1.資料庫連接池: DriverManagerDataSource 也可以使用DBCP2-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${db.jdbc.driverClassName}"/>
<property name="url" value="${db.jdbc.url}"/>
<property name="username" value="${db.jdbc.username}"/>
<property name="password" value="${db.jdbc.password}"/>
</bean>
<!-- 2.配置SqlSessionFactory物件 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 注入資料庫連接池 -->
<property name="dataSource" ref="dataSource"/>
<!-- 配置MyBaties全域組態檔:mybatis-config.xml -->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<!-- 掃描entity包 使用別名 -->
<property name="typeAliasesPackage" value="org.itstack.demo.po"/>
<!-- 掃描sql組態檔:mapper需要的xml檔案 -->
<property name="mapperLocations" value="classpath:mapper/*.xml"/>
</bean>
<!-- 3.配置掃描Dao介面包,動態實作Dao介面,注入到spring容器中 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 注入sqlSessionFactory -->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!-- 給出需要掃描Dao介面包,多個逗號隔開 -->
<property name="basePackage" value="org.itstack.demo.dao"/>
</bean>
</beans>
如果一切順利,那么會有如下結果:
{"address":"北京市海淀區頤和園路5號","createTime":1571376957000,"id":1,"name":"北京大學","updateTime":1571376957000}
{"age":18,"createTime":1571376957000,"id":1,"name":"花花","updateTime":1571376957000}
從上面單元測驗的代碼可以看到,兩個沒有方法體的注解就這么神奇的執行了我們的xml中的配置陳述句并輸出了結果,其實主要得益于以下兩個類;
- org.mybatis.spring.SqlSessionFactoryBean
- org.mybatis.spring.mapper.MapperScannerConfigurer
2. 掃描裝配注冊(MapperScannerConfigurer)
MapperScannerConfigurer為整個Dao介面層生成動態代理類注冊,啟動到了核心作用,這個類實作了如下介面,用來對掃描的Mapper進行處理:
- BeanDefinitionRegistryPostProcessor
- InitializingBean
- ApplicationContextAware
- BeanNameAware
整體類圖如下;

執行流程如下;

上面的類圖+流程圖,其實已經很清楚的描述了MapperScannerConfigurer初始化程序,但對于頭一次看的新人來說依舊是我太難了,好繼續!
MapperScannerConfigurer.java & 部分截取
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) {
if (this.processPropertyPlaceHolders) {
processPropertyPlaceHolders();
}
ClassPathMapperScanner scanner = new ClassPathMapperScanner(registry);
scanner.setAddToConfig(this.addToConfig);
scanner.setAnnotationClass(this.annotationClass);
scanner.setMarkerInterface(this.markerInterface);
scanner.setSqlSessionFactory(this.sqlSessionFactory);
scanner.setSqlSessionTemplate(this.sqlSessionTemplate);
scanner.setSqlSessionFactoryBeanName(this.sqlSessionFactoryBeanName);
scanner.setSqlSessionTemplateBeanName(this.sqlSessionTemplateBeanName);
scanner.setResourceLoader(this.applicationContext);
scanner.setBeanNameGenerator(this.nameGenerator);
scanner.registerFilters();
scanner.scan(StringUtils.tokenizeToStringArray(this.basePackage, ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS));
}
- 實作了BeanDefinitionRegistryPostProcessor.postProcessBeanDefinitionRegistry用于注冊Bean到Spring容器中
- 306行:new ClassPathMapperScanner(registry); 硬編碼類路徑掃描器,用于決議Mybatis的Mapper檔案
- 317行:scanner.scan 對Mapper進行掃描,這里包含了一個繼承類實作關系的呼叫,也就是本文開頭的測驗題,
ClassPathMapperScanner.java & 部分截取
@Override
public Set<BeanDefinitionHolder> doScan(String... basePackages) {
Set<BeanDefinitionHolder> beanDefinitions = super.doScan(basePackages);
if (beanDefinitions.isEmpty()) {
logger.warn("No MyBatis mapper was found in '" + Arrays.toString(basePackages) + "' package. Please check your configuration.");
} else {
processBeanDefinitions(beanDefinitions);
}
return beanDefinitions;
}
- 優先呼叫父類的super.doScan(basePackages);進行注冊Bean資訊
ClassPathBeanDefinitionScanner.java & 部分截取
protected Set<BeanDefinitionHolder> doScan(String... basePackages) {
Assert.notEmpty(basePackages, "At least one base package must be specified");
Set<BeanDefinitionHolder> beanDefinitions = new LinkedHashSet<BeanDefinitionHolder>();
for (String basePackage : basePackages) {
Set<BeanDefinition> candidates = findCandidateComponents(basePackage);
for (BeanDefinition candidate : candidates) {
ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(candidate);
candidate.setScope(scopeMetadata.getScopeName());
String beanName = this.beanNameGenerator.generateBeanName(candidate, this.registry);
if (candidate instanceof AbstractBeanDefinition) {
postProcessBeanDefinition((AbstractBeanDefinition) candidate, beanName);
}
if (candidate instanceof AnnotatedBeanDefinition) {
AnnotationConfigUtils.processCommonDefinitionAnnotations((AnnotatedBeanDefinition) candidate)
}
if (checkCandidate(beanName, candidate)) {
BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(candidate, beanName);
definitionHolder =
AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.regi
beanDefinitions.add(definitionHolder);
registerBeanDefinition(definitionHolder, this.registry);
}
}
}
return beanDefinitions;
}
- 優先呼叫了父類的doScan方法,用于Mapper掃描和Bean的定義以及注冊到DefaultListableBeanFactory,{DefaultListableBeanFactory是Spring中IOC容器的始祖,所有需要實體化的類都需要注冊進來,之后在初始化}
- 272行:findCandidateComponents(basePackage),掃描package包路徑,對于注解類的有另外的方式,大同小異
- 288行:registerBeanDefinition(definitionHolder, this.registry);注冊Bean資訊的程序,最侄訓呼叫到:org.springframework.beans.factory.support.DefaultListableBeanFactory
ClassPathMapperScanner.java & 部分截取
**processBeanDefinitions(beanDefinitions);**
private void processBeanDefinitions(Set<BeanDefinitionHolder> beanDefinitions) {
GenericBeanDefinition definition;
for (BeanDefinitionHolder holder : beanDefinitions) {
definition = (GenericBeanDefinition) holder.getBeanDefinition();
if (logger.isDebugEnabled()) {
logger.debug("Creating MapperFactoryBean with name '" + holder.getBeanName()
+ "' and '" + definition.getBeanClassName() + "' mapperInterface");
}
// the mapper interface is the original class of the bean
// but, the actual class of the bean is MapperFactoryBean
definition.getConstructorArgumentValues().addGenericArgumentValue(definition.getBeanClassName()); // issue #59
definition.setBeanClass(this.mapperFactoryBean.getClass());
definition.getPropertyValues().add("addToConfig", this.addToConfig);
boolean explicitFactoryUsed = false;
if (StringUtils.hasText(this.sqlSessionFactoryBeanName)) {
definition.getPropertyValues().add("sqlSessionFactory", new RuntimeBeanReference(this.sqlSessionFactoryBeanName));
explicitFactoryUsed = true;
} else if (this.sqlSessionFactory != null) {
definition.getPropertyValues().add("sqlSessionFactory", this.sqlSessionFactory);
explicitFactoryUsed = true;
}
if (StringUtils.hasText(this.sqlSessionTemplateBeanName)) {
if (explicitFactoryUsed) {
logger.warn("Cannot use both: sqlSessionTemplate and sqlSessionFactory together. sqlSessionFactory is ignored.");
}
definition.getPropertyValues().add("sqlSessionTemplate", new RuntimeBeanReference(this.sqlSessionTemplateBeanName));
explicitFactoryUsed = true;
} else if (this.sqlSessionTemplate != null) {
if (explicitFactoryUsed) {
logger.warn("Cannot use both: sqlSessionTemplate and sqlSessionFactory together. sqlSessionFactory is ignored.");
}
definition.getPropertyValues().add("sqlSessionTemplate", this.sqlSessionTemplate);
explicitFactoryUsed = true;
}
if (!explicitFactoryUsed) {
if (logger.isDebugEnabled()) {
logger.debug("Enabling autowire by type for MapperFactoryBean with name '" + holder.getBeanName() + "'.");
}
definition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);
}
}
}
- 163行:super.doScan(basePackages);,呼叫完父類方法后開始執行內部方法:processBeanDefinitions(beanDefinitions)
- 186行:definition.getConstructorArgumentValues().addGenericArgumentValue(definition.getBeanClassName()); 設定BeanName引數,也就是我們的:ISchoolDao、IUserDao
- 187行:definition.setBeanClass(this.mapperFactoryBean.getClass());,設定BeanClass,介面本身是沒有類的,那么這里將MapperFactoryBean類設定進來,最終所有的dao層介面類都是這個MapperFactoryBean
MapperFactoryBean.java & 部分截取
這個類有繼承也有介面實作,最好先了解下整體類圖,如下;

這個類就非常重要了,最終所有的sql資訊執行都會通過這個類獲取getObject(),也就是SqlSession獲取mapper的代理類:MapperProxyFactory->MapperProxy
public class MapperFactoryBean<T> extends SqlSessionDaoSupport implements FactoryBean<T> {
private Class<T> mapperInterface;
private boolean addToConfig = true;
public MapperFactoryBean() {
//intentionally empty
}
public MapperFactoryBean(Class<T> mapperInterface) {
this.mapperInterface = mapperInterface;
}
/**
* 當SpringBean容器初始化時候會呼叫到checkDaoConfig(),他是繼承類中的抽象方法
* {@inheritDoc}
*/
@Override
protected void checkDaoConfig() {
super.checkDaoConfig();
notNull(this.mapperInterface, "Property 'mapperInterface' is required");
Configuration configuration = getSqlSession().getConfiguration();
if (this.addToConfig && !configuration.hasMapper(this.mapperInterface)) {
try {
configuration.addMapper(this.mapperInterface);
} catch (Exception e) {
logger.error("Error while adding the mapper '" + this.mapperInterface + "' to configuration.", e);
throw new IllegalArgumentException(e);
} finally {
ErrorContext.instance().reset();
}
}
}
/**
* {@inheritDoc}
*/
@Override
public T getObject() throws Exception {
return getSqlSession().getMapper(this.mapperInterface);
}
...
}
-
72行:checkDaoConfig(),當SpringBean容器初始化時候會呼叫到checkDaoConfig(),他是繼承類中的抽象方法
-
95行:getSqlSession().getMapper(this.mapperInterface);,通過介面獲取Mapper(代理類),呼叫程序如下;
-
DefaultSqlSession.getMapper(Class type),獲取Mapper
-
Configuration.getMapper(Class type, SqlSession sqlSession),從配置中獲取
-
MapperRegistry.getMapper(Class type, SqlSession sqlSession),從注冊中心獲取到實體化生成
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); } } -
mapperProxyFactory.newInstance(sqlSession);,通過反射工程生成MapperProxy
@SuppressWarnings("unchecked") 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); }
-
MapperProxy.java & 部分截取
public class MapperProxy<T> implements InvocationHandler, Serializable {
private static final long serialVersionUID = -6424540398559729838L;
private final SqlSession sqlSession;
private final Class<T> mapperInterface;
private final Map<Method, MapperMethod> methodCache;
public MapperProxy(SqlSession sqlSession, Class<T> mapperInterface, Map<Method, MapperMethod> methodCache) {
this.sqlSession = sqlSession;
this.mapperInterface = mapperInterface;
this.methodCache = methodCache;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
if (Object.class.equals(method.getDeclaringClass())) {
return method.invoke(this, args);
} else if (isDefaultMethod(method)) {
return invokeDefaultMethod(proxy, method, args);
}
} catch (Throwable t) {
throw ExceptionUtil.unwrapThrowable(t);
}
final MapperMethod mapperMethod = cachedMapperMethod(method);
return mapperMethod.execute(sqlSession, args);
}
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;
}
@UsesJava7
private Object invokeDefaultMethod(Object proxy, Method method, Object[] args)
throws Throwable {
final Constructor<MethodHandles.Lookup> constructor = MethodHandles.Lookup.class
.getDeclaredConstructor(Class.class, int.class);
if (!constructor.isAccessible()) {
constructor.setAccessible(true);
}
final Class<?> declaringClass = method.getDeclaringClass();
return constructor
.newInstance(declaringClass,
MethodHandles.Lookup.PRIVATE | MethodHandles.Lookup.PROTECTED
| MethodHandles.Lookup.PACKAGE | MethodHandles.Lookup.PUBLIC)
.unreflectSpecial(method, declaringClass).bindTo(proxy).invokeWithArguments(args);
}
...
}
-
58行:final MapperMethod mapperMethod = cachedMapperMethod(method);,從快取中獲取MapperMethod
-
59行:mapperMethod.execute(sqlSession, args);,執行SQL陳述句,并回傳結果(到這關于查詢獲取結果就到骨頭(干)層了);INSERT、UPDATE、DELETE、SELECT
public Object execute(SqlSession sqlSession, Object[] args) { Object result; switch (command.getType()) { case INSERT: { Object param = method.convertArgsToSqlCommandParam(args); result = rowCountResult(sqlSession.insert(command.getName(), param)); break; } case UPDATE: { Object param = method.convertArgsToSqlCommandParam(args); result = rowCountResult(sqlSession.update(command.getName(), param)); break; } case DELETE: { Object param = method.convertArgsToSqlCommandParam(args); result = rowCountResult(sqlSession.delete(command.getName(), param)); break; } case SELECT: if (method.returnsVoid() && method.hasResultHandler()) { executeWithResultHandler(sqlSession, args); result = null; } else if (method.returnsMany()) { result = executeForMany(sqlSession, args); } else if (method.returnsMap()) { result = executeForMap(sqlSession, args); } else if (method.returnsCursor()) { result = executeForCursor(sqlSession, args); } else { Object param = method.convertArgsToSqlCommandParam(args); result = sqlSession.selectOne(command.getName(), param); } break; case FLUSH: result = sqlSession.flushStatements(); break; default: throw new BindingException("Unknown execution method for: " + command.getName()); } if (result == null && method.getReturnType().isPrimitive() && !method.returnsVoid()) { throw new BindingException("Mapper method '" + command.getName() + " attempted to return null from a method with a primitive return type (" + method.getReturnType() + ")."); } return result; }
以上對于MapperScannerConfigurer這一層就分析完了,從掃描定義注入到為Spring容器準備Bean的資訊,代理、反射、SQL執行,基本就包括全部核心內容了,接下來在分析下SqlSessionFactoryBean
3. SqlSession容器工廠初始化(SqlSessionFactoryBean)
SqlSessionFactoryBean初始化程序中需要對一些自身內容進行處理,因此也需要實作如下介面;
- FactoryBean
- InitializingBean -> void afterPropertiesSet() throws Exception
- ApplicationListener

以上的流程其實已經很清晰的描述整個核心流程,但同樣對于新手上路會有障礙,那么!好,繼續!
SqlSessionFactoryBean.java & 部分截取
public void afterPropertiesSet() throws Exception {
notNull(dataSource, "Property 'dataSource' is required");
notNull(sqlSessionFactoryBuilder, "Property 'sqlSessionFactoryBuilder' is required");
state((configuration == null && configLocation == null) || !(configuration != null && configLocation != null),
"Property 'configuration' and 'configLocation' can not specified with together");
this.sqlSessionFactory = buildSqlSessionFactory();
}
- afterPropertiesSet(),InitializingBean介面為bean提供了初始化方法的方式,它只包括afterPropertiesSet方法,凡是繼承該介面的類,在初始化bean的時候都會執行該方法,
- 380行:buildSqlSessionFactory();內部方法構建,核心功能繼續往下看,
SqlSessionFactoryBean.java & 部分截取
protected SqlSessionFactory buildSqlSessionFactory() throws IOException {
Configuration configuration;
XMLConfigBuilder xmlConfigBuilder = null;
...
if (!isEmpty(this.mapperLocations)) {
for (Resource mapperLocation : this.mapperLocations) {
if (mapperLocation == null) {
continue;
}
try {
XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(mapperLocation.getInputStream(),
configuration, mapperLocation.toString(), configuration.getSqlFragments());
xmlMapperBuilder.parse();
} catch (Exception e) {
throw new NestedIOException("Failed to parse mapping resource: '" + mapperLocation + "'", e);
} finally {
ErrorContext.instance().reset();
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Parsed mapper file: '" + mapperLocation + "'");
}
}
} else {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Property 'mapperLocations' was not specified or no matching resources found");
}
}
return this.sqlSessionFactoryBuilder.build(configuration);
}
- 513行:for (Resource mapperLocation : this.mapperLocations) 回圈決議Mapper內容
- 519行:XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(…) 決議XMLMapperBuilder
- 521行:xmlMapperBuilder.parse() 執行決議,具體如下;
XMLMapperBuilder.java & 部分截取
public class XMLMapperBuilder extends BaseBuilder {
private final XPathParser parser;
private final MapperBuilderAssistant builderAssistant;
private final Map<String, XNode> sqlFragments;
private final String resource;
private void bindMapperForNamespace() {
String namespace = builderAssistant.getCurrentNamespace();
if (namespace != null) {
Class<?> boundType = null;
try {
boundType = Resources.classForName(namespace);
} catch (ClassNotFoundException e) {
//ignore, bound type is not required
}
if (boundType != null) {
if (!configuration.hasMapper(boundType)) {
// Spring may not know the real resource name so we set a flag
// to prevent loading again this resource from the mapper interface
// look at MapperAnnotationBuilder#loadXmlResource
configuration.addLoadedResource("namespace:" + namespace);
configuration.addMapper(boundType);
}
}
}
}
}
- 這里413行非常重要,configuration.addMapper(boundType);,真正到了添加Mapper到配置中心
MapperRegistry.java & 部分截取
public class MapperRegistry {
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);
}
}
}
}
}
- 67行:創建代理工程knownMappers.put(type, new MapperProxyFactory(type));
截至到這,MapperScannerConfigurer、SqlSessionFactoryBean,兩個類干的事情就相融合了;
-
第一個用于掃描Dao介面設定代理類注冊到IOC中,用于后續生成Bean物體類,MapperFactoryBean,并可以通過mapperInterface從Configuration獲取Mapper
-
另一個用于生成SqlSession工廠初始化,決議Mapper里的XML配置進行動態代理MapperProxyFactory->MapperProxy注入到Configuration的Mapper
-
最終在注解類的幫助下進行方法注入,等執行操作時候即可獲得動態代理物件,從而執行相應的CRUD操作
@Resource private ISchoolDao schoolDao; schoolDao.querySchoolInfoById(1L);
六、綜上總結
- 分析程序較長篇幅也很大,不一定一天就能看懂整個流程,但當耐下心來一點點研究,還是可以獲得很多的識訓的,以后在遇到這類的例外就可以迎刃而解了,同時也有助于面試、招聘!
- 之所以分析Mybatis最開始是想在Dao上加自定義注解,發現切面攔截不到,想到這是被動態代理的類,之后層層往往下扒直到MapperProxy.invoke!當然,Mybatis提供了自定義插件開發,
- 以上的原始碼分析只是對部分核心內容進行分析,如果希望了解全部可以參考資料;MyBatis 3原始碼深度決議,并除錯代碼,IDEA中還是很方便看原始碼的,包括可以查看類圖、呼叫順序等,
- mybatis、mybatis-spring中其實最重要的是將Mapper組態檔決議與介面類組裝成代理類進行映射,以此來方便對資料庫的CRUD操作,從原始碼分析后,可以獲得更多的編程經驗(套路),
- Mybatis相關鏈接;
- https://github.com/mybatis/mybatis-3
- https://mybatis.org/mybatis-3/zh/index.html
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/291636.html
標籤:java
