1. 程式人生 > 其它 >手擼MyBatis(一)原始碼解析

手擼MyBatis(一)原始碼解析

技術標籤:企業級框架mybatisjdbcjavamysql原始碼

概述

MyBatis是大家最熟悉的ORM框架,大家基本都會用,那如果面試官問到MyBatis的實現原理該如何回答呢?本文將帶大家過一下MyBatis的原始碼,好對MyBatis有一個更深刻的認識。

MyBatis的基本操作

先帶大家過一下MyBatis的使用過程,這裡是沒有整合Spring,就是純粹的MyBatis。
1)建立表:

drop table if exists user;
CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(32) NOT NULL COMMENT '使用者名稱稱',
  `birthday` date DEFAULT NULL COMMENT '生日',
  `sex` char(1) DEFAULT NULL COMMENT '性別',
  `address` varchar(256) DEFAULT NULL COMMENT '地址',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=27 DEFAULT CHARSET=utf8;

drop table if exists orders;
CREATE TABLE `orders` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(11) NOT NULL COMMENT '下單使用者id',
  `number` varchar(32) NOT NULL COMMENT '訂單號',
  `createtime` datetime NOT NULL COMMENT '建立訂單時間',
  `note` varchar(100) DEFAULT NULL COMMENT '備註',
  PRIMARY KEY (`id`),
  KEY `FK_orders_1` (`user_id`),
  CONSTRAINT `FK_orders_id` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;

insert  into `user`(`id`,`username`,`birthday`,`sex`,`address`) values (1,'王五',NULL,'2',NULL),(10,'張三','2014-07-10','1','北京市'),(16,'張小明',NULL,'1','河南鄭州'),(22,'陳小明',NULL,'1','河南鄭州'),(24,'張三丰',NULL,'1','河南鄭州'),(25,'陳小明',NULL,'1','河南鄭州'),(26,'王五',NULL,NULL,NULL);
insert  into `orders`(`id`,`user_id`,`number`,`createtime`,`note`) values (3,1,'1000010','2015-02-04 13:22:35',NULL),(4,1,'1000011','2015-02-03 13:22:41',NULL),(5,10,'1000012','2015-02-12 16:13:23',NULL);

2)新增Maven依賴:

<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>4.11</version>
  <scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
  <groupId>org.mybatis</groupId>
  <artifactId>mybatis</artifactId>
  <version>3.4.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <version>5.1.38</version>
</dependency>

3)jdbc配置檔案:
jdbc.properties

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test_db?useUnicode=true&characterEncoding=UTF-8&useSSL=true
username=root
password=123456

4)MyBatis配置檔案:config.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>
    <properties resource="jdbc.properties"></properties>
    <environments default="develop">
        <environment id="develop">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <!--<package name="com.qf.mbs.mapper"/>-->
        <mapper resource="com/qf/mbs/mapper/UserDAO.xml"/>
<mapper resource="com/qf/mbs/mapper/OrderDAO.xml"/>
    </mappers>
</configuration>

5)新增DAO介面:

public interface UserDAO {
    List<User> findAll();
    User findById(Integer id);
    void addUser(User user);
    void updateUser(User user);
    void deleteUser(Integer id);
}

public interface OrderDAO {
    List<Order> findAll();
    List<Order> findByMap(Map<String,String> where);
}

6)新增對映檔案:

<?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="com.qf.mbs.dao.UserDAO">
    <insert id="addUser" parameterType="com.qf.mbs.po.User">
        <selectKey keyProperty="id" resultType="int" order="AFTER">
            SELECT LAST_INSERT_ID()
        </selectKey>
        INSERT INTO USER (USERNAME,BIRTHDAY,SEX,ADDRESS) VALUES (#{username},#{birthday},#{sex},#{address})
    </insert>
    <update id="updateUser" parameterType="com.qf.mbs.po.User">
        UPDATE  USER set username=#{username},birthday=#{birthday},sex=#{sex},address=#{address} where id=#{id}
    </update>
    <delete id="deleteUser" parameterType="java.lang.Integer">
        DELETE FROM USER where id=#{id}
    </delete>
    <select id="findById" parameterType="java.lang.Integer" resultType="com.qf.mbs.po.User">
        SELECT * FROM USER where id=#{id}
    </select>
    <select id="findAll" resultType="com.qf.mbs.po.User">
        select * from user
    </select>
</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="com.qf.mbs.dao.OrderDAO">
    <resultMap id="OrderMap" type="com.qf.mbs.po.Order">
        <id property="id" column="id"/>
        <result property="number" column="number"/>
        <result property="createtime" column="createtime"/>
        <result property="note" column="note"/>
        <association property="user" javaType="com.qf.mbs.po.User">
            <id property="id" column="id"/>
            <result property="username" column="username"/>
            <result property="birthday" column="birthday"/>
            <result property="sex" column="sex"/>
            <result property="address" column="address"/>
        </association>
    </resultMap>
    <select id="findAll" resultMap="OrderMap">
        select * from orders o inner join user u on o.user_id = u.id
    </select>
    <select id="findByMap" resultMap="OrderMap">
        select * from orders o inner join user u on o.user_id = u.id
        <where>
            <if test="username != null">
                AND username = #{username}
            </if>
            <if test="number != null">
                AND number = #{number}
            </if>
        </where>
    </select>
</mapper>

7) 單元測試:

public class Test1 {

    SqlSessionFactory factory = null;
    {
        try {
            factory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("config.xml"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void testAddUser()  {
        SqlSession sqlSession = factory.openSession();
        UserDAO userDAO = sqlSession.getMapper(UserDAO.class);
        userDAO.addUser(new User(1,"張大四","1999-9-9","男","wuhan"));
        sqlSession.commit();
        sqlSession.close();
    }

   @Test
    public void testFindAll(){
        SqlSession sqlSession = factory.openSession();
        OrderDAO orderDAO = sqlSession.getMapper(OrderDAO.class);
        List<Order> orders = orderDAO.findAll();
        System.out.println(orders);
        sqlSession.close();
    }

    @Test
    public void testFindMap(){
        SqlSession sqlSession = factory.openSession();
        OrderDAO orderDAO = sqlSession.getMapper(OrderDAO.class);
        Map<String,String> where = new HashMap<>();
        where.put("username","王五");
        where.put("number","1000010");
        List<Order> orders = orderDAO.findByMap(where);
        System.out.println(orders);
        sqlSession.close();
    }
}

原始碼分析

接下來,我們從基本的MyBatis操作,看看MyBatis是如何完成一個數據庫操作的。
首先,建立SqlSessionFactoryBuilder物件,讀取配置檔案,然後建立DefaultSqlSessionFactory物件。
原始碼如下:

  public SqlSessionFactory build(Reader reader, String environment, Properties properties) {
    try {
      //通過XMLConfigBuilder解析配置檔案,封裝為Configuration物件
      XMLConfigBuilder parser = new XMLConfigBuilder(reader, environment, properties);
      //建立DefaultSessionFactory物件
      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.
      }
    }
  }

  //build方法
  public SqlSessionFactory build(Configuration config) {
    return new DefaultSqlSessionFactory(config);
  }

獲得SqlSessionFactory物件之後,通過openSession獲得SsqlSession。
原始碼如下:

  private SqlSession openSessionFromDataSource(ExecutorType execType,
 TransactionIsolationLevel level, boolean autoCommit) {
    Transaction tx = null;
    try {
      //獲得配置的環境
      final Environment environment = configuration.getEnvironment();
      final TransactionFactory transactionFactory = 
getTransactionFactoryFromEnvironment(environment);
      tx = transactionFactory.newTransaction(environment.getDataSource(), level, 
autoCommit);
      //建立一個執行器去執行SQL命令
      final Executor executor = configuration.newExecutor(tx, execType);
      //返回DefaultSqlSession物件
      return new DefaultSqlSession(configuration, executor, autoCommit);
    } catch (Exception e) {
      closeTransaction(tx); // may have fetched a connection so lets call close()
      throw ExceptionFactory.wrapException("Error opening session.  Cause: " + e, e);
    } finally {
      ErrorContext.instance().reset();
    }
  }

我們操作資料庫時需要先定義一個DAO的介面,然後通過SqlSession的getMapper獲得該介面的實現,那麼這個介面是如何實現的呢?

通過SqlSession從Configuration中獲取。
原始碼如下:

DefaultSqlSession:

 
  public <T> T getMapper(Class<T> type) {
    return configuration.<T>getMapper(type, this);
  }

Configuration:

  public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
    return mapperRegistry.getMapper(type, sqlSession);
  }

MapperRegistry:

  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:

  public T newInstance(SqlSession sqlSession) {
    final MapperProxy<T> mapperProxy = new MapperProxy<T>(sqlSession, mapperInterface, methodCache);
    return newInstance(mapperProxy);
  }

  protected T newInstance(MapperProxy<T> mapperProxy) {
	//最後就是使用動態代理實現了DAO介面
	return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
  }

然後動態代理是如何執行SQL命令的呢,看程式碼:

MapperProxy:

 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    if (Object.class.equals(method.getDeclaringClass())) {
      try {
        return method.invoke(this, args);
      } catch (Throwable t) {
        throw ExceptionUtil.unwrapThrowable(t);
      }
    }
    final MapperMethod mapperMethod = cachedMapperMethod(method);
    //主要是這裡執行對映的方法
    return mapperMethod.execute(sqlSession, args);
  }

MapperMethod:

  public Object execute(SqlSession sqlSession, Object[] args) {
Object result;
     //這邊就是判斷SQL的型別,然後分別執行增刪改查的操作
    if (SqlCommandType.INSERT == command.getType()) {
      Object param = method.convertArgsToSqlCommandParam(args);
      result = rowCountResult(sqlSession.insert(command.getName(), param));
    } else if (SqlCommandType.UPDATE == command.getType()) {
      Object param = method.convertArgsToSqlCommandParam(args);
      result = rowCountResult(sqlSession.update(command.getName(), param));
    } else if (SqlCommandType.DELETE == command.getType()) {
      Object param = method.convertArgsToSqlCommandParam(args);
      result = rowCountResult(sqlSession.delete(command.getName(), param));
    } else if (SqlCommandType.SELECT == command.getType()) {
      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 {
        Object param = method.convertArgsToSqlCommandParam(args);
        result = sqlSession.selectOne(command.getName(), param);
      }
    } else {
      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;
  }

看一下selectList的實現:

public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) {
    try {
      MappedStatement ms = configuration.getMappedStatement(statement);
      //交給執行器區執行SQL
      return executor.query(ms, wrapCollection(parameter), 
rowBounds, Executor.NO_RESULT_HANDLER);
    } catch (Exception e) {
      throw ExceptionFactory.wrapException("Error querying database.  Cause: " + e, e);
    } finally {
      ErrorContext.instance().reset();
    }
  }

Executor有多種實現,看看SimpleExecutor:

public <E> List<E> doQuery(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
    Statement stmt = null;
    try {
      Configuration configuration = ms.getConfiguration();
      StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql);
      stmt = prepareStatement(handler, ms.getStatementLog());
      //用JDBC的Statement去執行命令了
      return handler.<E>query(stmt, resultHandler);
    } finally {
      closeStatement(stmt);
    }
  }

query方法的實現:

public <E> List<E> query(Statement statement, ResultHandler resultHandler) throws SQLException {
     //獲得PreparedStatement,執行命令
    PreparedStatement ps = (PreparedStatement) statement;
    ps.execute();
    //結果由ResultSetHandler 處理
    return resultSetHandler.<E> handleResultSets(ps);
  }

總結

最後我們梳理一下MyBatis整個執行過程:

  1. 通過SQLSessionFactoryBuilder建立SQLSessionFactory時,將核心配置檔案中configuration節點的內容,解析到SQLSessionFactory中
  2. 通過SQLSessionFactory獲得SqlSession時,返回DefaultSqlSession
  3. 呼叫SQLSessionFactory的getMapper方法時,返回了Mapper介面的動態代理物件,代理物件在invoke方法中實現了增刪改查操作
  4. 具體的增刪改查操作通過JDBC的Statement介面實現