從 0 開始手寫一個(gè) Mybatis 框架,三步搞定!

繼上一篇手寫SpringMVC之后,我最近趁熱打鐵,研究了一下Mybatis。MyBatis框架的核心功能其實(shí)不難,無非就是動(dòng)態(tài)代理和jdbc的操作,難的是寫出來可擴(kuò)展,高內(nèi)聚,低耦合的規(guī)范的代碼。本文完成的Mybatis功能比較簡(jiǎn)單,代碼還有許多需要改進(jìn)的地方,大家可以結(jié)合Mybatis源碼去動(dòng)手完善。

一、Mybatis框架流程簡(jiǎn)介

image.png

在手寫自己的Mybatis框架之前,我們先來了解一下Mybatis,它的源碼中使用了大量的設(shè)計(jì)模式,閱讀源碼并觀察設(shè)計(jì)模式在其中的應(yīng)用,才能夠更深入的理解源碼(ref:Mybatis源碼解讀-設(shè)計(jì)模式總結(jié))。我們對(duì)上圖進(jìn)行分析總結(jié):

  1. mybatis的配置文件有2類

    • mybatisconfig.xml,配置文件的名稱不是固定的,配置了全局的參數(shù)的配置,全局只能有一個(gè)配置文件。
    • Mapper.xml 配置多個(gè)statemement,也就是多個(gè)sql,整個(gè)mybatis框架中可以有多個(gè)Mappe.xml配置文件。
  2. 通過mybatis配置文件得到SqlSessionFactory

  3. 通過SqlSessionFactory得到SqlSession,用SqlSession就可以操作數(shù)據(jù)了。

  4. SqlSession通過底層的Executor(執(zhí)行器),執(zhí)行器有2類實(shí)現(xiàn):
    image
    • 基本實(shí)現(xiàn)
    • 帶有緩存功能的實(shí)現(xiàn)
  5. MappedStatement是通過Mapper.xml中定義statement生成的對(duì)象。

  6. 參數(shù)輸入執(zhí)行并輸出結(jié)果集,無需手動(dòng)判斷參數(shù)類型和參數(shù)下標(biāo)位置,且自動(dòng)將結(jié)果集映射為Java對(duì)象

    • HashMap,KV格式的數(shù)據(jù)類型
    • Java的基本數(shù)據(jù)類型
    • POJO,java的對(duì)象

二、梳理自己的Mybatis的設(shè)計(jì)思路

根據(jù)上文Mybatis流程,我簡(jiǎn)化了下,分為以下步驟:


image.png

1.讀取xml文件,建立連接

從圖中可以看出,MyConfiguration負(fù)責(zé)與人交互。待讀取xml后,將屬性和連接數(shù)據(jù)庫(kù)的操作封裝在MyConfiguration對(duì)象中供后面的組件調(diào)用。本文將使用dom4j來讀取xml文件,它具有性能優(yōu)異和非常方便使用的特點(diǎn)。

2.創(chuàng)建SqlSession,搭建Configuration和Executor之間的橋梁

我們經(jīng)常在使用框架時(shí)看到Session,Session到底是什么呢?一個(gè)Session僅擁有一個(gè)對(duì)應(yīng)的數(shù)據(jù)庫(kù)連接。類似于一個(gè)前段請(qǐng)求Request,它可以直接調(diào)用exec(SQL)來執(zhí)行SQL語句。從流程圖中的箭頭可以看出,MySqlSession的成員變量中必須得有MyExecutor和MyConfiguration去集中做調(diào)配,箭頭就像是一種關(guān)聯(lián)關(guān)系。我們自己的MySqlSession將有一個(gè)getMapper方法,然后使用動(dòng)態(tài)代理生成對(duì)象后,就可以做數(shù)據(jù)庫(kù)的操作了。

3.創(chuàng)建Executor,封裝JDBC操作數(shù)據(jù)庫(kù)

Executor是一個(gè)執(zhí)行器,負(fù)責(zé)SQL語句的生成和查詢緩存(緩存還沒完成)的維護(hù),也就是jdbc的代碼將在這里完成,不過本文只實(shí)現(xiàn)了單表,有興趣的同學(xué)可以嘗試完成多表。

4.創(chuàng)建MapperProxy,使用動(dòng)態(tài)代理生成Mapper對(duì)象

我們只是希望對(duì)指定的接口生成一個(gè)對(duì)象,使得執(zhí)行它的時(shí)候能運(yùn)行一句sql罷了,而接口無法直接調(diào)用方法,所以這里使用動(dòng)態(tài)代理生成對(duì)象,在執(zhí)行時(shí)還是回到MySqlSession中調(diào)用查詢,最終由MyExecutor做JDBC查詢。這樣設(shè)計(jì)是為了單一職責(zé),可擴(kuò)展性更強(qiáng)。

三、實(shí)現(xiàn)自己的Mybatis

工程文件及目錄:

image.png

首先,新建一個(gè)maven項(xiàng)目,在pom.xml中導(dǎo)入以下依賴:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.liugh</groupId>
  <artifactId>liugh-mybatis</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
         <!-- 讀取xml文件 -->
        <dependency>
            <groupId>dom4j</groupId>
            <artifactId>dom4j</artifactId>
            <version>1.6.1</version>
        </dependency>

        <!-- MySQL -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.29</version>
        </dependency>
    </dependencies>
</project>

創(chuàng)建我們的數(shù)據(jù)庫(kù)xml配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<database>
    <property name="driverClassName">com.mysql.jdbc.Driver</property>
    <property name="url">jdbc:mysql://localhost:3306/test?useUnicode=true&amp;characterEncoding=utf8</property>
    <property name="username">root</property>
    <property name="password">123456</property>
</database>

然后在數(shù)據(jù)庫(kù)創(chuàng)建test庫(kù),執(zhí)行如下SQL語句:

CREATE TABLE `user` (
  `id` varchar(64) NOT NULL,
  `password` varchar(255) DEFAULT NULL,
  `username` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
INSERT INTO `test`.`user` (`id`, `password`, `username`) VALUES ('1', '123456', 'liugh');

創(chuàng)建User實(shí)體類,和UserMapper接口和對(duì)應(yīng)的xml文件:

package com.liugh.bean;

public class User {
    private String id;
    private String username;
    private String password;
    //省略get set toString方法...
}

package com.liugh.mapper;

import com.liugh.bean.User;

public interface UserMapper {

    public User getUserById(String id);  
}

<?xml version="1.0" encoding="UTF-8"?>
<mapper nameSpace="com.liugh.mapper.UserMapper">
    <select id="getUserById" resultType ="com.liugh.bean.User">
        select * from user where id = ?
    </select>
</mapper>

基本操作配置完成,接下來我們開始實(shí)現(xiàn)MyConfiguration:

package com.liugh.sqlSession;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import com.liugh.config.Function;
import com.liugh.config.MapperBean;

/**
 * 讀取與解析配置信息,并返回處理后的Environment
 */
public class MyConfiguration {
    private static ClassLoader loader = ClassLoader.getSystemClassLoader();

    /**
     * 讀取xml信息并處理
     */
    public  Connection build(String resource){
        try {
            InputStream stream = loader.getResourceAsStream(resource);
            SAXReader reader = new SAXReader();
            Document document = reader.read(stream);
            Element root = document.getRootElement();
            return evalDataSource(root);
        } catch (Exception e) {
            throw new RuntimeException("error occured while evaling xml " + resource);
        }
    }

    private  Connection evalDataSource(Element node) throws ClassNotFoundException {
        if (!node.getName().equals("database")) {
            throw new RuntimeException("root should be <database>");
        }
        String driverClassName = null;
        String url = null;
        String username = null;
        String password = null;
        //獲取屬性節(jié)點(diǎn)
        for (Object item : node.elements("property")) {
            Element i = (Element) item;         
            String value = getValue(i);
            String name = i.attributeValue("name");
            if (name == null || value == null) {
                throw new RuntimeException("[database]: <property> should contain name and value");
            }
            //賦值
            switch (name) {
                case "url" : url = value; break;
                case "username" : username = value; break;
                case "password" : password = value; break;
                case "driverClassName" : driverClassName = value; break; 
                default : throw new RuntimeException("[database]: <property> unknown name"); 
            }
        }

         Class.forName(driverClassName); 
         Connection connection = null;
        try {
            //建立數(shù)據(jù)庫(kù)鏈接
            connection = DriverManager.getConnection(url, username, password);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return connection;
    }

    //獲取property屬性的值,如果有value值,則讀取 沒有設(shè)置value,則讀取內(nèi)容
    private  String getValue(Element node) {
        return node.hasContent() ? node.getText() : node.attributeValue("value");
    }

    @SuppressWarnings("rawtypes")
    public  MapperBean readMapper(String path){
        MapperBean mapper = new MapperBean();
        try{
            InputStream stream = loader.getResourceAsStream(path);
            SAXReader reader = new SAXReader();
            Document document = reader.read(stream);
            Element root = document.getRootElement();
            mapper.setInterfaceName(root.attributeValue("nameSpace").trim()); //把mapper節(jié)點(diǎn)的nameSpace值存為接口名
            List<Function> list = new ArrayList<Function>(); //用來存儲(chǔ)方法的List
            for(Iterator rootIter = root.elementIterator();rootIter.hasNext();) {//遍歷根節(jié)點(diǎn)下所有子節(jié)點(diǎn)
                Function fun = new Function();    //用來存儲(chǔ)一條方法的信息
                Element e = (Element) rootIter.next(); 
                String sqltype = e.getName().trim();
                String funcName = e.attributeValue("id").trim();
                String sql = e.getText().trim();
                String resultType = e.attributeValue("resultType").trim();
                fun.setSqltype(sqltype);
                fun.setFuncName(funcName);
                Object newInstance=null;
                try {
                    newInstance = Class.forName(resultType).newInstance();
                } catch (InstantiationException e1) {
                    e1.printStackTrace();
                } catch (IllegalAccessException e1) {
                    e1.printStackTrace();
                } catch (ClassNotFoundException e1) {
                    e1.printStackTrace();
                }
                fun.setResultType(newInstance);
                fun.setSql(sql);
                list.add(fun);
            }
            mapper.setList(list);

        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return mapper;
    }
}

用面向?qū)ο蟮乃枷朐O(shè)計(jì)讀取xml配置后:

package com.liugh.config;

import java.util.List;
public class MapperBean {
    private String interfaceName; //接口名
    private List<Function> list; //接口下所有方法
    //省略 get  set方法...
}

Function對(duì)象包括sql的類型、方法名、sql語句、返回類型和參數(shù)類型。

package com.liugh.config;

public class Function {
    private String sqltype;  
    private String funcName;  
    private String sql;       
    private Object resultType;  
    private String parameterType; 
    //省略 get set方法
}

接下來實(shí)現(xiàn)我們的MySqlSession,首先的成員變量里得有Excutor和MyConfiguration,代碼的精髓就在getMapper的方法里。

package com.liugh.sqlSession;

import java.lang.reflect.Proxy;

public class MySqlsession {

    private Excutor excutor= new MyExcutor();  

    private MyConfiguration myConfiguration = new MyConfiguration();

    public <T> T selectOne(String statement,Object parameter){  
        return excutor.query(statement, parameter);  
    }  

    @SuppressWarnings("unchecked")
    public <T> T getMapper(Class<T> clas){ 
        //動(dòng)態(tài)代理調(diào)用
        return (T)Proxy.newProxyInstance(clas.getClassLoader(),new Class[]{clas},
                new MyMapperProxy(myConfiguration,this));  
    }  

}

緊接著創(chuàng)建Excutor和實(shí)現(xiàn)類:

package com.liugh.sqlSession;

public interface Excutor {
    public <T> T query(String statement,Object parameter);  
}

MyExcutor中封裝了JDBC的操作:

package com.liugh.sqlSession;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.liugh.bean.User;

public class MyExcutor implements Excutor{

    private MyConfiguration xmlConfiguration = new MyConfiguration();

     @Override  
        public <T> T query(String sql, Object parameter) {  
            Connection connection=getConnection();  
            ResultSet set =null;
            PreparedStatement pre =null;
            try {  
                pre = connection.prepareStatement(sql); 
                //設(shè)置參數(shù)
                pre.setString(1, parameter.toString());
                set = pre.executeQuery();  
                User u=new User();  
                //遍歷結(jié)果集
                while(set.next()){  
                    u.setId(set.getString(1));
                    u.setUsername(set.getString(2)); 
                    u.setPassword(set.getString(3));
                }  
                return (T) u;  
            } catch (SQLException e) {  
                e.printStackTrace();  
            } finally{
                   try{  
                       if(set!=null){  
                           set.close();  
                       }if(pre!=null){  
                           pre.close();  
                       }if(connection!=null){  
                           connection.close();  
                       }  
                   }catch(Exception e2){  
                       e2.printStackTrace();  
                   }  
               }   
            return null;  
        }  

        private Connection getConnection() {  
            try {  
                Connection connection =xmlConfiguration.build("config.xml");
                return connection;  
            } catch (Exception e) {  
                e.printStackTrace();  
            }  
            return null;  
        }  
}

MyMapperProxy代理類完成xml方法和真實(shí)方法對(duì)應(yīng),執(zhí)行查詢:

package com.liugh.sqlSession;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.List;
import com.liugh.config.Function;
import com.liugh.config.MapperBean;

public class MyMapperProxy implements InvocationHandler{

    private  MySqlsession mySqlsession;  

    private MyConfiguration myConfiguration;

    public MyMapperProxy(MyConfiguration myConfiguration,MySqlsession mySqlsession) {  
        this.myConfiguration=myConfiguration;  
        this.mySqlsession=mySqlsession;  
    }  

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        MapperBean readMapper = myConfiguration.readMapper("UserMapper.xml");
        //是否是xml文件對(duì)應(yīng)的接口
        if(!method.getDeclaringClass().getName().equals(readMapper.getInterfaceName())){
            return null;  
        }
        List<Function> list = readMapper.getList();
        if(null != list || 0 != list.size()){
            for (Function function : list) {
            //id是否和接口方法名一樣
             if(method.getName().equals(function.getFuncName())){  
                    return mySqlsession.selectOne(function.getSql(), String.valueOf(args[0]));  
                }  
            }
        }
         return null;  
    }
}

到這里,就完成了自己的Mybatis框架,我們測(cè)試一下:

package com.liugh;

import com.liugh.bean.User;
import com.liugh.mapper.UserMapper;
import com.liugh.sqlSession.MySqlsession;

public class TestMybatis {

    public static void main(String[] args) {  
        MySqlsession sqlsession=new MySqlsession();  
        UserMapper mapper = sqlsession.getMapper(UserMapper.class);  
        User user = mapper.getUserById("1");  
        System.out.println(user);
    } 
}

執(zhí)行結(jié)果:


image.png

查詢一個(gè)不存在的用戶試試:

image.png

到這里我們就大功告成了!

我是個(gè)普通的程序猿,水平有限,文章難免有錯(cuò)誤,歡迎犧牲自己寶貴時(shí)間的讀者,就本文內(nèi)容直抒己見,我的目的僅僅是希望對(duì)讀者有所幫助。源碼地址:https://github.com/qq53182347/liugh-mybatis

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容