幾百行代碼寫個Mybatis,原理搞的透透的!

做者:小傅哥
博客:bugstack.cnhtml

沉澱、分享、成長,讓本身和他人都能有所收穫!😄java

1、前言

Mybatis 最核心的原理也是它最便於使用的體現,爲何這說?node

由於咱們在使用 Mybatis 的時候,只須要定義一個不須要寫實現類的接口,就能經過註解或者配置SQL語句的方式,對數據庫進行 CRUD 操做。mysql

那麼這是怎麼作到的呢,其中有一點很是重要,就是在 Spring 中能夠把你的代理對象交給 Spring 容器,這個代理對象就是能夠當作是 DAO 接口的具體實現類,而這個被代理的實現類就能夠完成對數據庫的一個操做,也就是這個封裝過程被稱爲 ORM 框架。git

說了基本的流程,咱們來作點測試,讓你們能夠動手操做起來!學知識,必定是上手,才能獲得!你能夠經過如下源碼倉庫進行練習github

github.com/fuzhengwei/…web


2、把Bean塞到Spring容器,分幾步

Bean註冊

  • 關於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 中,以上這部分代碼主要的內容包括:spring

  • 實現 BeanDefinitionRegistryPostProcessor.postProcessBeanDefinitionRegistry方法,獲取 Bean 註冊對象。
  • 定義 Bean,GenericBeanDefinition,這裏主要設置了咱們的代理類工廠。
  • 建立 Bean 定義處理類,BeanDefinitionHolder,這裏須要的主要參數;定義 Bean 和名稱 setBeanClass(ProxyBeanFactory.class)
  • 最後將咱們本身的bean註冊到spring容器中去,registry.registerBeanDefinition()

5. 測試驗證

在上面咱們已經把自定義代理的 Bean 註冊到了 Spring 容器中,接下來咱們來測試下這個代理的 Bean 被如何調用。sql

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 框架都須要使用到。

3、手寫個Mybatis

擴展上一篇源碼分析工程;itstack-demo-mybatis,增長 like 包,模仿 Mybatis 工程。完整規程下載 github.com/fuzhengwei/…

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,直到往下以此作了;

  1. 獲取 ClassLoader 集合,最大限度搜索配置文件
  2. 經過 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
複製代碼

4、源碼分析(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工廠類建立的,而不是直接使用構造器。容器的配置文件加載和初始化流程以下:

微信公衆號:bugstack蟲洞棧 & 初始化流程

  • 流程核心類
    • 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);
  }
  ...
}  
複製代碼
  1. XMLConfigBuilder對於XML文件的加載和解析都委託於XPathParser,最終使用JDK自帶的javax.xml進行XML解析(XPath)
  2. XPathParser(Reader reader, boolean validation, Properties variables, EntityResolver entityResolver)
    1. reader:使用字符流建立新的輸入源,用於對XML文件的讀取
    2. validation:是否進行DTD校驗
    3. variables:屬性配置信息
    4. 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;
  }

}
複製代碼
  1. Mybatis依賴於dtd文件進行進行解析,其中的ibatis-3-config.dtd主要是用於兼容用途
  2. 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);
  }
  
}    
複製代碼
  1. 從上到下能夠看到主要是爲了建立一個Mybatis的文檔解析器,最後根據builder.parse(inputSource)返回Document

  2. 獲得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;
     }
    複製代碼
  3. 其中調用了父類的構造函數

    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();
      }
    }
    複製代碼
  4. 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文件解析和裝載的核心內容,其中包括;

  1. 屬性解析propertiesElement
  2. 加載settings節點settingsAsProperties
  3. 載自定義VFS loadCustomVfs
  4. 解析類型別名typeAliasesElement
  5. 加載插件pluginElement
  6. 加載對象工廠objectFactoryElement
  7. 建立對象包裝器工廠objectWrapperFactoryElement
  8. 加載反射工廠reflectorFactoryElement
  9. 元素設置settingsElement
  10. 加載環境配置environmentsElement
  11. 數據庫廠商標識加載databaseIdProviderElement
  12. 加載類型處理器typeHandlerElement
  13. (核心)加載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 )返回最終節點內容,能夠參考mybatis.org/dtd/mybatis…

<!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個配置文件,以下;

  1. properties?,
  2. settings?,
  3. typeAliases?,
  4. typeHandlers?,
  5. objectFactory?,
  6. objectWrapperFactory?,
  7. reflectorFactory?,
  8. plugins?,
  9. environments?,
  10. databaseIdProvider?,
  11. 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 {
        ...
      }
    }
  }
}
複製代碼

微信公衆號:bugstack蟲洞棧 & 動態代理過程

Mapper加載到生成代理對象的流程中,主要的核心類包括;

  1. XMLConfigBuilder
  2. Configuration
  3. MapperRegistry
  4. MapperAnnotationBuilder
  5. 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。

5、綜上總結

  • 分析過程較長篇幅也很大,不必定一天就能看懂整個流程,但當耐下心來一點點研究,仍是能夠得到不少的收穫的。之後在遇到這類的異常就能夠迎刃而解了,同時也有助於面試、招聘!
  • 之因此分析Mybatis最開始是想在Dao上加自定義註解,發現切面攔截不到。想到這是被動態代理的類,以後層層每每下扒直到MapperProxy.invoke!固然,Mybatis提供了自定義插件開發。
  • 以上的源碼分析只是對部分核心內容進行分析,若是但願瞭解所有能夠參考資料;MyBatis 3源碼深度解析,並調試代碼。IDEA中仍是很方便看源碼的,包括能夠查看類圖、調用順序等。
  • mybatis、mybatis-spring中其實最重要的是將Mapper配置文件解析與接口類組裝成代理類進行映射,以此來方便對數據庫的CRUD操做。從源碼分析後,能夠得到更多的編程經驗(套路)。
  • Mybatis相關連接;
相關文章
相關標籤/搜索