小試自定義mybaits框架

在這裏插入圖片描述

前言

上篇淺析mybatis執行原理,仿照mybatis做一個自定義的orm映射框架。理了思路,先寫下要實現哪些功能,這個文檔會持續更新,對應的代碼也會持續更新下去。

  • 支持xml和註解的方式將我們的mapper定義sql獲取,即以下兩種配置
<!--使用xml寫sql-->
<!--<mapper resource="mybatis/DeptEmpMapper.xml"></mapper>-->

<!--註解sql-->
<mapper class="fast.cloud.nacos.mybatis.mapper.DeptEmpMapper"></mapper>
  • xxxMapper.java文件添加jdk動態代理,這樣是爲了統一實現使用jdbc去查詢,而不用每個都去寫實現。
  • 實現數據庫字段和實體屬性,這個用註解實現。
  • 儘量遵循mybatis框架的設計風格。

實現

pom依賴

<!-- 日誌座標 -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.12</version>
        </dependency>
        <!-- 解析xml的dom4j -->
        <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.6</version>
        </dependency>
        <!-- dom4j的依賴包jaxen -->
        <dependency>
            <groupId>jaxen</groupId>
            <artifactId>jaxen</artifactId>
            <version>1.1.6</version>
        </dependency>

定義全局配置Configuration

在看mybatis源碼的時候,它會把所有的xml配置文件映射成一個Configuration對象。所以這裏也建一個,代碼如下:

import fast.cloud.nacos.custom.mybatis.mapper.Mapper;

import java.util.Map;

/**
 * 核心配置類
 * 1.數據庫信息
 * 2.sql 的 map 集合
 */
public class Configuration {

    private String username; //用戶名
    private String password;//密碼
    private String url;//地址
    private String driver;//驅動
    //map 集合 Map<唯一標識,Mapper> 用於保存映射文件中的 sql 標識及 sql 語句
    private Map<String, Mapper> mappers;
    //key爲column,value爲properties
    private Map<String,String> typeAliasesMap;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getDriver() {
        return driver;
    }

    public void setDriver(String driver) {
        this.driver = driver;
    }

    public Map<String, Mapper> getMappers() {
        return mappers;
    }

    public void setMappers(Map<String, Mapper> mappers) {
        this.mappers = mappers;
    }

    public Map<String, String> getTypeAliasesMap() {
        return typeAliasesMap;
    }

    public void setTypeAliasesMap(Map<String, String> typeAliasesMap) {
        this.typeAliasesMap = typeAliasesMap;
    }
}

xml解析類XMLConfigBuilder

將配置的xml解析成Configuration,還要注意的是兩種方式,第一種loadMapperConfiguration,讀取我們自己的xxxMapper.xml裏面的sql,還有一種方式是讀取xxxMapper.java文件,這種方式我們可以讀取註解裏面的sql。殊途同歸,兩種方式都要符合一個規範。

  • 類的全限定名+.+方法名作爲唯一的key(mybatis爲了更加唯一,前面還加上了uuid,這裏不做那麼複雜)
  • 把讀到sql,以及返回類型封裝起來最爲value,這裏這個對象叫做Mapper.java

代碼如下:


/**
 * 用於解析配置文件
 */
public class XMLConfigBuilder {
    /**
     * 解析主配置文件,把裏面的內容填充到 DefaultSqlSession 所需要的地方
     * 使用的技術:
     * dom4j+xpath
     *
     * @param session
     */

    public static void loadConfiguration(DefaultSqlSession session, InputStream
            config) {
        try {
            //定義封裝連接信息的配置對象(mybatis 的配置對象)
            Configuration cfg = new Configuration();
            //1.獲取 SAXReader 對象
            SAXReader reader = new SAXReader();
            //2.根據字節輸入流獲取 Document 對象
            Document document = reader.read(config);
            //3.獲取根節點
            Element root = document.getRootElement();
            //4.使用 xpath 中選擇指定節點的方式,獲取所有 property 節點
            List<Element> propertyElements = root.selectNodes("//property");
            //5.遍歷節點
            for (Element propertyElement : propertyElements) {
                //判斷節點是連接數據庫的哪部分信息
                //取出 name 屬性的值
                String name = propertyElement.attributeValue("name");
                if ("driver".equals(name)) {
                    //表示驅動
                    //獲取 property 標籤 value 屬性的值
                    String driver = propertyElement.attributeValue("value");
                    cfg.setDriver(driver);
                }
                if ("url".equals(name)) {
                    //表示連接字符串
                    //獲取 property 標籤 value 屬性的值
                    String url = propertyElement.attributeValue("value");
                    cfg.setUrl(url);
                }
                if ("username".equals(name)) {
                    //表示用戶名
                    //獲取 property 標籤 value 屬性的值
                    String username = propertyElement.attributeValue("value");
                    cfg.setUsername(username);
                }
                if ("password".equals(name)) {
                    //表示密碼
                    //獲取 property 標籤 value 屬性的值
                    String password = propertyElement.attributeValue("value");
                    cfg.setPassword(password);
                }
            }
            //獲取mappers 中package標籤package標籤
            List<Element> packageElements = root.selectNodes("//mappers/package");
            if (!CollectionUtils.isEmpty(packageElements)) {
                Element element = packageElements.get(0);
                String packageName = element.attribute("name").getValue();
                Set<Class<?>> mapperSet = ClassUtil.getClasses(packageName);
                mapperSet.forEach(clz -> {
                    String className = clz.getName();
                    Method method = clz.getMethods()[0];
                    String methodName = method.getName();
                    String returnType = method.getReturnType().getName();
                    String key = className + "." + methodName;

//                    String id = selectElement.attributeValue("id");
//                    //取出 resultType 屬性的值 組成 map 中 value 的部分
//                    String resultType = selectElement.attributeValue("resultType");
//                    //取出文本內容 組成 map 中 value 的部分
//                    String queryString = selectElement.getText();
//                    //創建 Key
//                    String key = namespace + "." + id;
//                    //創建 Value
//                    Mapper mapper = new Mapper();
//                    mapper.setQueryString(queryString);
//                    mapper.setResultType(resultType);
//                    //把 key 和 value 存入 mappers 中
//                    mappers.put(key, mapper);
                });

            } else {
                //取出 mappers 中的所有 mapper 標籤,判斷他們使用了 resource 還是 class 屬性
                List<Element> mapperElements = root.selectNodes("//mappers/mapper");
                //遍歷集合
                for (Element mapperElement : mapperElements) {
                    //判斷 mapperElement 使用的是哪個屬性
                    Attribute attribute = mapperElement.attribute("resource");
                    if (attribute != null) {
                        System.out.println("使用的是 XML");
                        //表示有 resource 屬性,用的是 XML
                        //取出屬性的值
                        String mapperPath = attribute.getValue();// 獲 取 屬 性 的 值 "com/dao/IUserDao.xml"
                        //把映射配置文件的內容獲取出來,封裝成一個 map
                        Map<String, Mapper> mappers = loadMapperConfiguration(mapperPath);
                        //給 configuration 中的 mappers 賦值
                        cfg.setMappers(mappers);
                    } else {
                        System.out.println("使用的是註解");
                        //表示沒有 resource 屬性,用的是註解
                        //獲取 class 屬性的值
                        String daoClassPath = mapperElement.attributeValue("class");
                        //根據 daoClassPath 獲取封裝的必要信息
                        Map<String, Mapper> mappers = loadMapperAnnotation(daoClassPath);
                        //給 configuration 中的 mappers 賦值
                        cfg.setMappers(mappers);
                    }
                }
            }

            List<Element> typeAliasesElements = root.selectNodes("//typeAliases/package");
            //2. 解析實體類中的註解拿到映射數據
            if (!CollectionUtils.isEmpty(typeAliasesElements)) {
                String packageName = typeAliasesElements.get(0).attribute("name").getValue();
                Set<Class<?>> entitySet = ClassUtil.getClasses(packageName);
                Map<String, String> colProMap = new HashMap<>();
                entitySet.forEach(clz -> {
                    Field[] fields = clz.getDeclaredFields();
                    Stream.of(fields).forEach(field -> {
                        String proName = field.getName();
                        ORMColumn annotation = field.getAnnotation(ORMColumn.class);
                        if (annotation != null) {
                            String colName = annotation.name();
                            colProMap.put(colName, proName);
                        }
                    });
                });
                cfg.setTypeAliasesMap(colProMap);
            }


            //把配置對象傳遞給 DefaultSqlSession
            session.setCfg(cfg);

        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            try {
                config.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 根據傳入的參數,解析 XML,並且封裝到 Map 中
     *
     * @param mapperPath 映射配置文件的位置
     * @return map 中包含了獲取的唯一標識(key 是由 dao 的全限定類名和方法名組成)
     * 以及執行所需的必要信息(value 是一個 Mapper 對象,裏面存放的是執行的 SQL 語句和
     * 要封裝的實體類全限定類名)
     */
    private static Map<String, Mapper> loadMapperConfiguration(String mapperPath) throws IOException {
        InputStream in = null;
        try {
            //定義返回值對象
            Map<String, Mapper> mappers = new HashMap<String, Mapper>();
            //1.根據路徑獲取字節輸入流
            in = Resources.getResourceAsStream(mapperPath);
            //2.根據字節輸入流獲取 Document 對象
            SAXReader reader = new SAXReader();
            Document document = reader.read(in);
            //3.獲取根節點
            Element root = document.getRootElement();
            //4.獲取根節點的 namespace 屬性取值
            String namespace = root.attributeValue("namespace");//是組成 map 中 key 的部分
            //5.獲取所有的 select 節點
            List<Element> selectElements = root.selectNodes("//select");
            //6.遍歷 select 節點集合
            for (Element selectElement : selectElements) {
                //取出 id 屬性的值 組成 map 中 key 的部分
                String id = selectElement.attributeValue("id");
                //取出 resultType 屬性的值 組成 map 中 value 的部分
                String resultType = selectElement.attributeValue("resultType");
                //取出文本內容 組成 map 中 value 的部分
                String queryString = selectElement.getText();
                //創建 Key
                String key = namespace + "." + id;
                //創建 Value
                Mapper mapper = new Mapper();
                mapper.setQueryString(queryString);
                mapper.setResultType(resultType);
                //把 key 和 value 存入 mappers 中
                mappers.put(key, mapper);
            }
            return mappers;
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            in.close();
        }
    }

    /**
     * 根據傳入的參數,得到 dao 中所有被 select 註解標註的方法。
     * 根據方法名稱和類名,以及方法上註解 value 屬性的值,組成 Mapper 的必要信息
     *
     * @param daoClassPath
     * @return
     */
    private static Map<String, Mapper> loadMapperAnnotation(String daoClassPath) throws Exception {
        //定義返回值對象
        Map<String, Mapper> mappers = new HashMap<String, Mapper>();
        //1.得到 dao 接口的字節碼對象
        Class daoClass = Class.forName(daoClassPath);
        //2.得到 dao 接口中的方法數組
        Method[] methods = daoClass.getMethods();
        //3.遍歷 Method 數組
        for (Method method : methods) {
            //取出每一個方法,判斷是否有 select 註解
            boolean isAnnotated = method.isAnnotationPresent(Select.class);
            if (isAnnotated) {
                //創建 Mapper 對象
                Mapper mapper = new Mapper();
                //取出註解的 value 屬性值
                Select selectAnno = method.getAnnotation(Select.class);
                String queryString = selectAnno.value();
                mapper.setQueryString(queryString);
                //獲取當前方法的返回值,還要求必須帶有泛型信息
                Type type = method.getGenericReturnType();//List<User>
                //判斷 type 是不是參數化的類型
                if (type instanceof ParameterizedType) {
                    //強轉
                    ParameterizedType ptype = (ParameterizedType) type;
                    //得到參數化類型中的實際類型參數
                    Type[] types = ptype.getActualTypeArguments();
                    //取出第一個
                    Class domainClass = (Class) types[0];
                    //獲取 domainClass 的類名
                    String resultType = domainClass.getName();
                    //給 Mapper 賦值
                    mapper.setResultType(resultType);
                }
                //組裝 key 的信息
                //獲取方法的名稱
                String methodName = method.getName();
                String className = method.getDeclaringClass().getName();
                String key = className + "." + methodName;
                //給 map 賦值
                mappers.put(key, mapper);
            }
        }
        return mappers;
    }
}

數據庫打交道的SqlSession系列

抽象工廠SqlSessionFactory

/**
 * SqlSessionFactory 的接口
 */
public interface SqlSessionFactory {
    /**
     * 創建一個新的 SqlSession 對象
     */
    SqlSession openSession();
}

默認實現工廠DefaultSqlSessionFactory

/**
 * SqlSessionFactory 的默認實現
 */
public class DefaultSqlSessionFactory implements SqlSessionFactory {
    private InputStream config = null;

    public void setConfig(InputStream config) {
        this.config = config;
    }

    @Override
    public SqlSession openSession() {
        DefaultSqlSession session = new DefaultSqlSession();
        //調用工具類解析 xml 文件
        XMLConfigBuilder.loadConfiguration(session, config);
        return session;
    }
}

默認實現DefaultSqlSession

public class DefaultSqlSession implements SqlSession {
    //核心配置對象
    private Configuration cfg;

    public void setCfg(Configuration cfg) {
        this.cfg = cfg;
    }

    //連接對象
    private Connection conn;

    //調用 DataSourceUtils 工具類獲取連接
    public Connection getConn() {

        try {
            conn = DataSourceUtil.getConnection(cfg);
            return conn;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 動態代理:
     * 涉及的類:Proxy
     * 使用的方法:newProxyInstance
     * 方法的參數:
     * ClassLoader:和被代理對象使用相同的類加載器,通常都是固定的
     * Class[]:代理對象和被代理對象要求有相同的行爲。(具有相同的方法)
     * InvocationHandler:如何代理。需要我們自己提供的增強部分的代碼
     */
    @Override
    public <T> T getMapper(Class<T> daoClass) {
        conn = getConn();
        System.out.println(conn);
        T daoProxy = (T) Proxy.newProxyInstance(daoClass.getClassLoader(), new
                Class[]{daoClass}, new MapperProxyFactory(cfg.getMappers(), conn, cfg.getTypeAliasesMap()));
        return daoProxy;
    }

    //釋放資源
    @Override
    public void close() {
        try {
            System.out.println(conn);
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    //查詢所有方法
    public <E> List<E> selectList(String statement) {
        Mapper mapper = cfg.getMappers().get(statement);
        Map<String, String> typeAliasesMap = cfg.getTypeAliasesMap();
        return new Executor().selectList(mapper, typeAliasesMap, conn);
    }
}

建造者模式SqlSessionFactoryBuilder

public class SqlSessionFactoryBuilder {
    /**
     * 根據傳入的流,實現對 SqlSessionFactory 的創建
     *
     * @param in 它就是 SqlMapConfig.xml 的配置以及裏面包含的 IUserDao.xml 的配置
     * @return
     */
    public SqlSessionFactory build(InputStream in) {
        DefaultSqlSessionFactory factory = new DefaultSqlSessionFactory();
        //給 factory 中 config 賦值
        factory.setConfig(in);
        return factory;
    }
}

動態代理MapperProxyFactory

這個是重頭戲,取出當前執行的方法名稱以及取出當前執行的方法所在類,找到對應的mapper統一執行sql,封裝結果,返回。

public class MapperProxyFactory implements InvocationHandler {
    private Map<String, Mapper> mappers;
    private Connection conn;
    private Map<String, String> typeAliasesMap;

    public MapperProxyFactory(Map<String, Mapper> mappers, Connection conn, Map<String, String> typeAliasesMap) {
        this.mappers = mappers;
        this.conn = conn;
        this.typeAliasesMap = typeAliasesMap;
    }

    /**
     * 對當前正在執行的方法進行增強
     * 取出當前執行的方法名稱
     * 取出當前執行的方法所在類
     * 拼接成 key
     * 去 Map 中獲取 Value(Mapper)
     * 使用工具類 Executor 的 selectList 方法x
     */
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //1.取出方法名
        String methodName = method.getName();
        //2.取出方法所在類名
        String className = method.getDeclaringClass().getName();
        //3.拼接成 Key
        String key = className + "." + methodName;
        //4.使用 key 取出 mapper
        Mapper mapper = mappers.get(key);
        if (mapper == null) {
            throw new IllegalArgumentException("傳入的參數有誤,無法獲取執行的必要條件 ");
        }
        //5.創建 Executor 對象
        Executor executor = new Executor();
        return executor.selectList(mapper, typeAliasesMap, conn);
    }
}

執行器Executor

jdbc的封裝,這裏有個typeAliasesMap,做下字段和屬性的映射關係。

/**
 * 負責執行 SQL 語句,並且封裝結果集
 */
public class Executor {
    public <E> List<E> selectList(Mapper mapper, Map<String, String> typeAliasesMap, Connection conn) {
        PreparedStatement pstm = null;
        ResultSet rs = null;
        try {
            //1.取出 mapper 中的數據
            String queryString = mapper.getQueryString();//select * from user
            String resultType = mapper.getResultType();//com.domain.User
            Class domainClass = Class.forName(resultType);//User.class
            //2.獲取 PreparedStatement 對象
            pstm = conn.prepareStatement(queryString);
            //3.執行 SQL 語句,獲取結果集
            rs = pstm.executeQuery();
            //4.封裝結果集
            List<E> list = new ArrayList<E>();//定義返回值
            while (rs.next()) {
                //實例化要封裝的實體類對象
                E obj = (E) domainClass.newInstance();//User 對象
                //取出結果集的元信息:ResultSetMetaData
                ResultSetMetaData rsmd = rs.getMetaData();
                //取出總列數
                int columnCount = rsmd.getColumnCount();
                //遍歷總列數
                for (int i = 1; i <= columnCount; i++) {
                    //獲取每列的名稱,列名的序號是從 1 開始的
                    String columnName = rsmd.getColumnName(i);
                    //根據得到列名,獲取每列的值
                    Object columnValue = rs.getObject(columnName);
                    String proName = typeAliasesMap.getOrDefault(columnName, columnName);
                    //給 obj 賦值:使用 Java 內省機制(藉助 PropertyDescriptor 實現屬性的封裝)
                    PropertyDescriptor pd = new
                            PropertyDescriptor(proName, domainClass);//要求:實體類的屬性和數據庫表的列名保持一種
                    //獲取它的寫入方法
                    Method writeMethod = pd.getWriteMethod();//setUsername(String username);
                    //把獲取的列的值,給對象賦值
                    writeMethod.invoke(obj, columnValue);
                }
                //把賦好值的對象加入到集合中
                list.add(obj);
            }
            return list;
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            release(pstm, rs);
        }
    }

    private void release(PreparedStatement pstm, ResultSet rs) {
        if (rs != null) {
            try {
                rs.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (pstm != null) {
            try {
                pstm.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

測試

測試前準備,需要把jar依賴過來,以及配置xml,還有就是定義實體,mapper,這裏還繼續延續上節的代碼,測試。

測試xml方式

  • 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>
    <typeAliases>  <!--配置實體類的別名-->
        <package name="fast.cloud.nacos.mybatis.entity"/>
    </typeAliases>

    <environments default="MySQLDevelopment">
        <environment id="MySQLDevelopment">
            <transactionManager type="JDBC"></transactionManager> <!--事務-->
            <dataSource type="POOLED">  <!--數據庫連接-->
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/demo?characterEncoding=utf-8"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <!--使用xml寫sql-->
        <mapper resource="mybatis/DeptEmpMapper.xml"></mapper>
    </mappers>

</configuration>
  • 測試方法
@Test
    public void testMybatis() throws IOException {
        //1. 加載核心配置文件
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");

        //2. 解析核心配置文件並創建SqlSessionFactory對象
        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);

        //3. 創建核心對象
        SqlSession sqlSession = sqlSessionFactory.openSession();

        //4. 得到Mapper代理對象
        DeptEmpMapper deptEmpMapper = sqlSession.getMapper(DeptEmpMapper.class);

        //5. 調用自定義的方法實現查詢功能
        List<DeptEmp> list = deptEmpMapper.getEmpTotalByDept();
        for (DeptEmp de : list) {
            System.out.println(de);
        }

        //6. 關閉sqlSession
        sqlSession.close();

    }

運行結果

在這裏插入圖片描述

測試註解方式

  • 添加註解的sql
//Mapper接口  不用編寫實現類
public interface DeptEmpMapper {

    @Select("SELECT deptno, COUNT(*) AS total  FROM  emp  GROUP BY deptno")
    List<DeptEmp> getEmpTotalByDept();

}
  • 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>
    <typeAliases>  <!--配置實體類的別名-->
        <package name="fast.cloud.nacos.mybatis.entity"/>
    </typeAliases>

    <environments default="MySQLDevelopment">
        <environment id="MySQLDevelopment">
            <transactionManager type="JDBC"></transactionManager> <!--事務-->
            <dataSource type="POOLED">  <!--數據庫連接-->
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/demo?characterEncoding=utf-8"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <!--使用xml寫sql-->
        <!--<mapper resource="mybatis/DeptEmpMapper.xml"></mapper>-->

        <!--註解sql-->
        <mapper class="fast.cloud.nacos.mybatis.mapper.DeptEmpMapper"></mapper>
        <!--<package name="fast.cloud.nacos.mybatis.mapper"/>-->
    </mappers>

</configuration>
  • 測試方法不變,運行結果如下:

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章