【不說(shuō)廢話】MyBatis系列(一):手寫(xiě)簡(jiǎn)單持久層框架

不說(shuō)廢話,直接開(kāi)始

分析jdbc操作問(wèn)題

思考

jdbc已經(jīng)能夠完成數(shù)據(jù)庫(kù)的操作,已經(jīng)能完成增刪該查的操作,為什么改需要 MyBatis 呢?

原因

jdbc操作存在一些問(wèn)題,哪些問(wèn)題?通過(guò) jdbc 代碼分析

public static void main(String[] args) { 
    Connection connection = null; 
    PreparedStatement preparedStatement = null; 
    ResultSet resultSet = null; 
    try { 
        
        // 加載數(shù)據(jù)庫(kù)驅(qū)動(dòng) 
        Class.forName("com.mysql.jdbc.Driver"); 
        // 通過(guò)驅(qū)動(dòng)管理類獲取數(shù)據(jù)庫(kù)鏈接 
        connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8", "root", "root");
        
        // 定義sql語(yǔ)句?表示占位符 
        String sql = "select * from user where username = ?"; 
        // 獲取預(yù)處理statement 
        preparedStatement = connection.prepareStatement(sql); 
        // 設(shè)置參數(shù),第?個(gè)參數(shù)為sql語(yǔ)句中參數(shù)的序號(hào)(從1開(kāi)始),第?個(gè)參數(shù)為設(shè)置的參數(shù)值
        preparedStatement.setString(1, "tom"); 
        // 向數(shù)據(jù)庫(kù)發(fā)出sql執(zhí)?查詢,查詢出結(jié)果集 
        resultSet = preparedStatement.executeQuery(); 
        
        // 遍歷查詢結(jié)果集 
        while (resultSet.next()) { 
            int id = resultSet.getInt("id"); 
            String username = resultSet.getString("username"); 
            // 封裝User 
            user.setId(id); 
            user.setUsername(username); 
        } 
        System.out.println(user); 
    } 
    
} catch (Exception e) { 
    e.printStackTrace(); 
} finally { 
    // 釋放資源 
    if (resultSet != null) { 
        try { resultSet.close(); 
            } catch (SQLException e) { 
            e.printStackTrace(); 
        }
    }
    if (preparedStatement != null) { 
        try { 
            preparedStatement.close(); 
        } catch (SQLException e) { 
            e.printStackTrace(); 
        }
    }
    if (connection != null) { 
        try { connection.close(); 
            } catch (SQLException e) { 
            e.printStackTrace(); 
        } 
    }
}

畫(huà)圖分析

jdbc問(wèn)題分析.png

問(wèn)題總結(jié)

  1. 數(shù)據(jù)庫(kù)的連接創(chuàng)建、釋放頻繁造成系統(tǒng)資源浪費(fèi),從而影響系統(tǒng)性能
  2. sql語(yǔ)句在代碼中硬編碼,造成代碼不易維護(hù),實(shí)際應(yīng)用中sql變換的可能較大,sql變動(dòng)需要改變java代碼
  3. 使用prepared Statement向占有位符號(hào)傳參存在硬編碼,因?yàn)閟ql語(yǔ)句的where條件不一定,可能多也可能少,修改sql還要修改代碼,系統(tǒng)不易維護(hù)
  4. 對(duì)結(jié)果集解析存在硬編碼(查詢列名),sql變化導(dǎo)致解析代碼變化,系統(tǒng)不易維護(hù),如果能將數(shù)據(jù)庫(kù)的庫(kù)記錄封裝成pojo對(duì)象解析比較方便

問(wèn)題解決

  1. 使用數(shù)據(jù)庫(kù)連接池初始化連接資源
  2. 將sql語(yǔ)句抽取到xml配置文件中
  3. 使用反射、內(nèi)省等底層技術(shù),將自動(dòng)實(shí)現(xiàn)與表進(jìn)行屬性與字段的自動(dòng)映射

自定義持久層框架

設(shè)計(jì)思路

使用端(項(xiàng)目):

  • 引入自定義持久層框架的jar包
  • 使用配置文件提供兩部分配置信息
    • sqlMapConfig.xml:數(shù)據(jù)庫(kù)配置信息、mapper.xml的全路徑
    • mapper.xml:sql配置信息:sql語(yǔ)句、參數(shù)類型、返回值類型

自定義持久層框架本身(工程):本質(zhì)就是對(duì)JDBC代碼進(jìn)行封裝

  1. 加載配置文件:根據(jù)配置文件的路徑,加載配置文件成字節(jié)流,存儲(chǔ)在內(nèi)存中

    創(chuàng)建類:Resources 方法:InputSteam getResourceAsSteam(String path)

  2. 創(chuàng)建兩個(gè)javaBean(容器對(duì)象):存放的就是對(duì)配置文件解析出來(lái)的內(nèi)容

    Configuration(核心配置類):存放sqlMapConfig.xml解析出來(lái)的內(nèi)容

    MappedStatement(映射配置類):存放mapper.xml解析出來(lái)的內(nèi)容

  3. 解析配置文件:dom4j

    創(chuàng)建類:SqlSessionFactoryBuilder 方法:build(InputSteam in)

    (1) 使用dom4j解析配置文件,將解析出來(lái)的內(nèi)容封裝到容器對(duì)象中

    (2) 創(chuàng)建SqlSessionFactory對(duì)象:生產(chǎn)sqlSession(會(huì)話對(duì)象)--- 工廠模式

  4. 創(chuàng)建SqlSessionFactory接口及實(shí)現(xiàn)類DefaultSqlSessionFactory

    openSession( ):生產(chǎn)sqlSession

  5. 創(chuàng)建SqlSession接口及實(shí)現(xiàn)類DefaultSession

    定義對(duì)數(shù)據(jù)庫(kù)的crud操作:selectList( )、selectOne( )、update( )、delete( )

  6. 創(chuàng)建Executor接口及實(shí)現(xiàn)類SimpleExecutor實(shí)現(xiàn)類

    query(Configuration, MappedStatement, Object... params):執(zhí)行的就是JDBC代碼

圖解分析

自定義mybatis分析.jpg

代碼實(shí)現(xiàn)

創(chuàng)建Modules:IPersistence(自定義持久層框架)和 IPersistence_test(用戶端)

代碼實(shí)現(xiàn)中有詳細(xì)注釋?。?/p>

使用端

IPersistence_test

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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.zx</groupId>
    <artifactId>IPersistence_test</artifactId>
    <version>1.0-SNAPSHOT</version>

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

    <!-- 引入自定義持久層框架依賴 -->
    <dependencies>
        <dependency>
            <groupId>com.zx</groupId>
            <artifactId>IPersistence</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
    </dependencies>
</project>
sqlMapConfig.xml

數(shù)據(jù)庫(kù)配置信息、mapper.xml的全路徑

<configuration>
    <!-- 數(shù)據(jù)庫(kù)配置信息 -->
    <dataSource>
        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql:///zx_mybatis"></property>
        <property name="" value="root"></property>
        <property name="" value="root"></property>
    </dataSource>

    <!-- 存放mapper.xml的全路徑 -->
    <mapper resource="UserMapper.xml"></mapper>
</configuration>
UserMapper.xml

sql配置信息:sql語(yǔ)句、參數(shù)類型、返回值類型

<mapper namespace="user">
    <!-- sql的唯一標(biāo)識(shí):namespace.id來(lái)組成的 -->
    <select id="selectList" resultType="com.zx.pojo.User">
        select * from user
    </select>

    <select id="selectOne" resultType="com.zx.pojo.Use" paramterType="com.zx.pojo.Use">
        select * from user where id = #{id} and username = #{username}
    </select>
</mapper>
User
package com.zx.pojo;

import java.io.Serializable;

public class User implements Serializable {
    private Integer id;
    private String username;

    // getter... setter...
}
IPersistenceTest
package com.zx.test;

import com.zx.io.Resources;
import com.zx.pojo.User;
import com.zx.sqlSession.SqlSession;
import com.zx.sqlSession.SqlSessionFactory;
import com.zx.sqlSession.SqlSessionFactoryBuilder;
import org.junit.Test;

import java.io.InputStream;
import java.util.List;

public class IPersistenceTest {
    @Test
    public void test() throws Exception {
        InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        SqlSession sqlSession = sqlSessionFactory.openSqlSession();
        // 調(diào)用
        List<User> list = sqlSession.selectList("user.selectList");
        for (User user1 : list) {
            System.out.println(user1);
        }
    }
}

自定義持久層框架

IPersistence

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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.zx</groupId>
    <artifactId>IPersistence</artifactId>
    <version>1.0-SNAPSHOT</version>

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

    <dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.17</version>
        </dependency>

        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
        </dependency>

        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.12</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.10</version>
        </dependency>

        <dependency>
            <groupId>dom4j</groupId>
            <artifactId>dom4j</artifactId>
            <version>1.6.1</version>
        </dependency>

        <dependency>
            <groupId>jaxen</groupId>
            <artifactId>jaxen</artifactId>
            <version>1.1.6</version>
        </dependency>
    </dependencies>
</project>
Configuration
package com.zx.pojo;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * Configuration(核心配置類):存放sqlMapConfig.xml解析出來(lái)的內(nèi)容
 * Configuration 即包含了數(shù)據(jù)庫(kù)的配置信息:dataSource
 *               也包含了sql的配置信息:mappedStatementMap
 */
public class Configuration {
    /**
     * 存放數(shù)據(jù)源配置
     */
    private DataSource dataSource;
    /**
     * key:statementId
     * value:封裝好的 MappedStatement 對(duì)象
     */
    Map<String, MappedStatement> mappedStatementMap = new HashMap<>();

    // getter... setter...
}
MappedStatement
package com.zx.pojo;

/**
 * MappedStatement(映射配置類):存放mapper.xml解析出來(lái)的內(nèi)容
 */
public class MappedStatement {
    /**
     * id標(biāo)識(shí)
     */
    private String id;
    /**
     * 返回值類型
     */
    private String resultType;
    /**
     * 參數(shù)值類型
     */
    private String parameterType;
    /**
     * sql語(yǔ)句
     */
    private String sql;

    // getter... setter...
}
Resources
package com.zx.io;

import java.io.InputStream;

public class Resources {
    /**
     * 根據(jù)配置文件的路徑,將配置文件加載成字節(jié)輸入流,存儲(chǔ)在內(nèi)存中
     * @param path:使用端傳過(guò)來(lái)的配置文件的路徑
     * @return resourceAsStream:字節(jié)輸入流
     */
    public static InputStream getResourceAsStream(String path) {
        // 獲取類加載器
        InputStream resourceAsStream = Resources.class.getClassLoader().getResourceAsStream(path);
        return resourceAsStream;
    }
}
SqlSessionFactoryBuilder
package com.zx.sqlSession;

import com.zx.config.XMLConfigBuilder;
import com.zx.pojo.Configuration;
import org.dom4j.DocumentException;

import java.beans.PropertyVetoException;
import java.io.InputStream;

/**
 * 作用:
 *  1.使用dom4j解析配置文件,將解析出來(lái)的內(nèi)容封裝到容器對(duì)象中
 *  2.創(chuàng)建SqlSessionFactory對(duì)象,來(lái)生產(chǎn)sqlSession(會(huì)話對(duì)象)
 */
public class SqlSessionFactoryBuilder {
    public SqlSessionFactory build(InputStream in) throws DocumentException, PropertyVetoException {
        // 1.使用dom4j解析配置文件,將解析出來(lái)的內(nèi)容封裝到Configuration中
        XMLConfigBuilder xmlConfigBuilder = new XMLConfigBuilder();
        Configuration configuration = xmlConfigBuilder.parseConfig(in);
        // 2.創(chuàng)建sqlSessionFactory對(duì)象:工廠類:生產(chǎn)sqlSession:會(huì)話對(duì)象
        DefaultSqlSessionFactory defaultSqlSessionFactory = new DefaultSqlSessionFactory(configuration);
        return defaultSqlSessionFactory;
    }
}
XMLConfigBuilder
package com.zx.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.zx.io.Resources;
import com.zx.pojo.Configuration;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

public class XMLConfigBuilder {

    private Configuration configuration;
    public XMLConfigBuilder() {
        this.configuration = new Configuration();
    }
    /**
     * 該方法就是使用dom4j對(duì)配置文件解析,封裝Configuration
     * @param inputStream
     * @return
     */
    public Configuration parseConfig(InputStream inputStream) throws DocumentException, PropertyVetoException {
        /*
         * 對(duì) sqlMapConfig.xml 進(jìn)行解析,封裝Configuration
         */
        Document document = new SAXReader().read(inputStream);
        // 拿到sqlMapConfig.xml里的<configuration>
        Element rootElement = document.getRootElement();
        // 查找configuration里面的元素,"http://xxx"-表示xxx在配置文件的任意位置都能夠查找到
        List<Element> list = rootElement.selectNodes("http://property");
        Properties properties = new Properties();
        for (Element element : list) {
            // 獲取property標(biāo)簽里的 name 的值
            String name = element.attributeValue("name");
            // 獲取property標(biāo)簽里的 value 的值
            String value = element.attributeValue("value");
            // name 和 value 的值都封裝到 properties 里
            properties.setProperty(name, value);
        }
        // 使用c3p0連接池,創(chuàng)建連接池對(duì)象,將他們封裝到configuration這個(gè)對(duì)象中
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        comboPooledDataSource.setDriverClass(properties.getProperty("driverClass"));
        comboPooledDataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
        comboPooledDataSource.setUser(properties.getProperty("username"));
        comboPooledDataSource.setPassword(properties.getProperty("password"));
        configuration.setDataSource(comboPooledDataSource);
        /*
         * 對(duì) mapper.xml 進(jìn)行解析,封裝Configuration
         * 拿到路徑 -- 字節(jié)輸入流 -- dom4j進(jìn)行解析
         */
        List<Element> mapList = rootElement.selectNodes("http://mapper");
        // 每一個(gè)element就是對(duì)應(yīng)的sqlMapConfig.xml里的一個(gè)<mapper>標(biāo)簽
        // <mapper resource="UserMapper.xml"></mapper>
        for (Element element : mapList) {
            // 拿到路徑
            String mapperPath = element.attributeValue("resource");
            // 獲取字節(jié)輸入流
            InputStream resourceAsStream = Resources.getResourceAsStream(mapperPath);
            // dom4j進(jìn)行解析
            XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(configuration);
            xmlMapperBuilder.parse(resourceAsStream);
        }
        return configuration;
    }
}

XMLMapperBuilder
package com.zx.config;

import com.zx.pojo.Configuration;
import com.zx.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

public class XMLMapperBuilder {

    private Configuration configuration;
    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parse(InputStream inputStream) throws DocumentException {
        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();
        String namespace = rootElement.attributeValue("namespace");
        List<Element> list = rootElement.selectNodes("http://select");
        // element對(duì)應(yīng)的就是mapper.xml里的select語(yǔ)句標(biāo)簽
        for (Element element : list) {
            // 獲取每個(gè)標(biāo)簽的id,resultType,parameterType,sql語(yǔ)句
            String id = element.attributeValue("id");
            String resultType = element.attributeValue("resultType");
            String parameterType = element.attributeValue("parameterType");
            String sqlText = element.getTextTrim();
            // 封裝到MappedStatement實(shí)體類中
            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setId(id);
            mappedStatement.setResultType(resultType);
            mappedStatement.setParameterType(parameterType);
            mappedStatement.setSql(sqlText);
            // sql的唯一標(biāo)識(shí):statement  namespace.id
            String key = namespace +"."+ id;
            configuration.getMappedStatementMap().put(key, mappedStatement);
        }
    }
}
SqlSessionFactory
package com.zx.sqlSession;

public interface SqlSessionFactory {
    public SqlSession openSqlSession();
}
DefaultSqlSessionFactory
package com.zx.sqlSession;

import com.zx.pojo.Configuration;

public class DefaultSqlSessionFactory implements SqlSessionFactory {

    private Configuration configuration;
    public DefaultSqlSessionFactory(Configuration configuration) {
        this.configuration = configuration;
    }

    @Override
    public SqlSession openSqlSession() {
        return new DefaultSqlSession(configuration);
    }
}
SqlSession
package com.zx.sqlSession;

import java.util.List;

public interface SqlSession {
    /**
     * 查詢所有
     * @param statementId:對(duì)應(yīng) mapper.xml 里的sql唯一標(biāo)識(shí):namespace.id,Configuration中封裝的key值
     * @param params:按照條件查詢 模糊查詢
     * @param <E>
     * @return
     */
    public <E> List<E> selectList(String statementId, Object... params) throws Exception;
    /**
     *
     * @param statementId:對(duì)應(yīng) mapper.xml 里的sql唯一標(biāo)識(shí):namespace.id,Configuration中封裝的key值
     * @param params:按照條件查詢
     * @param <T>
     * @return
     */
    public <T> T selectOne(String statementId, Object... params) throws Exception;
}
DefaultSqlSession
package com.zx.sqlSession;

import com.zx.pojo.Configuration;
import com.zx.pojo.MappedStatement;

import java.util.List;

public class DefaultSqlSession implements SqlSession {

    private Configuration configuration;
    public DefaultSqlSession(Configuration configuration) {
        this.configuration = configuration;
    }

    @Override
    public <E> List<E> selectList(String statementId, Object... params) throws Exception {
        // 將要去完成對(duì)simpleExecutor里的query方法的調(diào)用
        SimpleExecutor simpleExecutor = new SimpleExecutor();
        MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementId);
        List<E> list = simpleExecutor.query(configuration, mappedStatement, params);
        return list;
    }

    @Override
    public <T> T selectOne(String statementId, Object... params) throws Exception {
        List<Object> objects = selectList(statementId, params);
        if (objects.size() == 1) {
            return (T) objects.get(0);
        }else {
            throw new RuntimeException("查詢結(jié)果為空或返回結(jié)果過(guò)多");
        }
    }
}
Executor
package com.zx.sqlSession;

import com.zx.pojo.Configuration;
import com.zx.pojo.MappedStatement;

import java.util.List;

public interface Executor {
    public <E> List<E> query(Configuration configuration, MappedStatement mappedStatement, Object... params) throws Exception;
}
SimpleExecutor
package com.zx.sqlSession;

import com.zx.config.BoundSql;
import com.zx.pojo.Configuration;
import com.zx.pojo.MappedStatement;
import com.zx.utils.GenericTokenParser;
import com.zx.utils.ParameterMapping;
import com.zx.utils.ParameterMappingTokenHandler;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;

public class SimpleExecutor implements Executor {
    @Override
    public <E> List<E> query(Configuration configuration, MappedStatement mappedStatement, Object... params) throws Exception {

        // 1.注冊(cè)驅(qū)動(dòng),獲取連接
        Connection connection = configuration.getDataSource().getConnection();

        // 2.獲取sql語(yǔ)句 select * from user where id = #{id} and username = #{username}
        //   轉(zhuǎn)換sql語(yǔ)句 select * from user where id = ? and username = ?,轉(zhuǎn)換過(guò)程中,還要對(duì)#{}里面的值進(jìn)行解析存儲(chǔ)
        String sql = mappedStatement.getSql();
        BoundSql boundSql = getBoundSql(sql);

        // 3.獲取預(yù)處理對(duì)象:preparedStatement
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());

        // 4.設(shè)置參數(shù)
            // 獲取參數(shù)的全路徑
        String parameterType = mappedStatement.getParameterType();
            // 根據(jù)參數(shù)的全路徑獲取它的class對(duì)象
        Class<?> parameterTypeClass = getClassType(parameterType);

        List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
        for (int i = 0; i < parameterMappingList.size(); i++) {
            // 取出parameterMappingList里的每一個(gè)對(duì)象
            ParameterMapping parameterMapping = parameterMappingList.get(i);
            // 取出#{}里面的內(nèi)容 id,username
            String content = parameterMapping.getContent();
            // 反射:通過(guò)content獲取實(shí)體類的屬性值
            Field declaredField = parameterTypeClass.getDeclaredField(content);
            // 設(shè)置暴力訪問(wèn)
            declaredField.setAccessible(true);
            // 設(shè)置參數(shù)
            Object o = declaredField.get(params[0]);
            preparedStatement.setObject(i+1, o);
        }

        // 5.執(zhí)行sql
        // 查詢出來(lái)的結(jié)果封裝在 resultSet 中
        ResultSet resultSet = preparedStatement.executeQuery();

        // 6.封裝返回結(jié)果集
        // 獲取返回值類型
        String resultType = mappedStatement.getResultType();
        // 轉(zhuǎn)為class對(duì)象(new PropertyDescriptor使用)
        Class<?> resultTypeClass = getClassType(resultType);
        // 用于存放封裝好的o
        ArrayList<Object> objects = new ArrayList<>();
        while (resultSet.next()) {
            // 獲取resultTypeClass的具體實(shí)現(xiàn),Object對(duì)象(writeMethod.invoke使用)
            Object o = resultTypeClass.newInstance();
            // 取出resultSet的元數(shù)據(jù),元數(shù)據(jù)中包含了字段名
            ResultSetMetaData metaData = resultSet.getMetaData();
            // metaData.getColumnCount()列的個(gè)數(shù),數(shù)據(jù)庫(kù)里有兩列,則小于等于2
            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                // 字段名 metaData.getColumnName(i)要從1開(kāi)始,所以定義為i=1開(kāi)始遍歷
                String columnName = metaData.getColumnName(i);
                // 字段的值
                Object value = resultSet.getObject(columnName);
                // 使用反射或者內(nèi)省,根據(jù)數(shù)據(jù)庫(kù)表和實(shí)體類的對(duì)應(yīng)關(guān)系,完成封裝
                // PropertyDescriptor類會(huì)將resultTypeClass對(duì)象中的columnName屬性生成讀寫(xiě)方法
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultTypeClass);
                // 獲取propertyDescriptor的寫(xiě)方法
                Method writeMethod = propertyDescriptor.getWriteMethod();
                // 把字段的值value封裝到對(duì)象o中
                writeMethod.invoke(o, value);
            }
            // 將封裝好的o存進(jìn)List集合中
            objects.add(o);
        }
        return (List<E>) objects;
    }

    private Class<?> getClassType(String parameterType) throws ClassNotFoundException {
        if (parameterType != null) {
            Class<?> aClass = Class.forName(parameterType);
            return aClass;
        }
        return null;
    }

    /**
     * 完成對(duì)#{}的解析工作
     *  1.將#{}使用?進(jìn)行代替
     *  2.解析出#{}里面的值進(jìn)行存儲(chǔ)
     * @param sql
     * @return
     */
    private BoundSql getBoundSql(String sql) {
        // 標(biāo)記處理類:配置標(biāo)記解析器來(lái)完成對(duì)占位符的解析處理工作
        ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler();
        // 標(biāo)記解析器  openToken:開(kāi)始標(biāo)記,closeToken:結(jié)束標(biāo)記,handler:標(biāo)記處理器
        GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", parameterMappingTokenHandler);
        // parseSql就是解析后的sql語(yǔ)句
        String parseSql = genericTokenParser.parse(sql);
        // parameterMappings就是解析出來(lái)的#{}參數(shù)名稱
        List<ParameterMapping> parameterMappings = parameterMappingTokenHandler.getParameterMappings();
        BoundSql boundSql = new BoundSql(parseSql, parameterMappings);
        return boundSql;
    }
}
BoundSql
package com.zx.config;

import com.zx.utils.ParameterMapping;

import java.util.ArrayList;
import java.util.List;

public class BoundSql {
    /**
     * 解析過(guò)后的sql
     */
    private String sqlText;
    /**
     * 解析出來(lái)的參數(shù)集合
     */
    private List<ParameterMapping> parameterMappingList = new ArrayList<>();

    public BoundSql(String sqlText, List<ParameterMapping> parameterMappingList) {
        this.sqlText = sqlText;
        this.parameterMappingList = parameterMappingList;
    }

    // getter... setter...
}
GenericTokenParser

(MyBatis源碼中粘貼)

package com.zx.utils;

public class GenericTokenParser {

    private final String openToken; //開(kāi)始標(biāo)記
    private final String closeToken; //結(jié)束標(biāo)記
    private final TokenHandler handler; //標(biāo)記處理器

    public GenericTokenParser(String openToken, String closeToken, TokenHandler handler) {
        this.openToken = openToken;
        this.closeToken = closeToken;
        this.handler = handler;
    }

    /**
     * 解析${}和#{}
     * @param text
     * @return
     * 該方法主要實(shí)現(xiàn)了配置文件、腳本等片段中占位符的解析、處理工作,并返回最終需要的數(shù)據(jù)。
     * 其中,解析工作由該方法完成,處理工作是由處理器handler的handleToken()方法來(lái)實(shí)現(xiàn)
     */
    public String parse(String text) {
        // 驗(yàn)證參數(shù)問(wèn)題,如果是null,就返回空字符串。
        if (text == null || text.isEmpty()) {
            return "";
        }
        // 下面繼續(xù)驗(yàn)證是否包含開(kāi)始標(biāo)簽,如果不包含,默認(rèn)不是占位符,直接原樣返回即可,否則繼續(xù)執(zhí)行。
        int start = text.indexOf(openToken, 0);
        if (start == -1) {
            return text;
        }
        // 把text轉(zhuǎn)成字符數(shù)組src,并且定義默認(rèn)偏移量offset=0、存儲(chǔ)最終需要返回字符串的變量builder,
        // text變量中占位符對(duì)應(yīng)的變量名expression。判斷start是否大于-1(即text中是否存在openToken),如果存在就執(zhí)行下面代碼
        char[] src = text.toCharArray();
        int offset = 0;
        final StringBuilder builder = new StringBuilder();
        StringBuilder expression = null;
        while (start > -1) {
            // 判斷如果開(kāi)始標(biāo)記前如果有轉(zhuǎn)義字符,就不作為openToken進(jìn)行處理,否則繼續(xù)處理
            if (start > 0 && src[start - 1] == '\\') {
                builder.append(src, offset, start - offset - 1).append(openToken);
                offset = start + openToken.length();
            } else {
                //重置expression變量,避免空指針或者老數(shù)據(jù)干擾。
                if (expression == null) {
                    expression = new StringBuilder();
                } else {
                    expression.setLength(0);
                }
                builder.append(src, offset, start - offset);
                offset = start + openToken.length();
                int end = text.indexOf(closeToken, offset);
                while (end > -1) {////存在結(jié)束標(biāo)記時(shí)
                    if (end > offset && src[end - 1] == '\\') {//如果結(jié)束標(biāo)記前面有轉(zhuǎn)義字符時(shí)
                        // this close token is escaped. remove the backslash and continue.
                        expression.append(src, offset, end - offset - 1).append(closeToken);
                        offset = end + closeToken.length();
                        end = text.indexOf(closeToken, offset);
                    } else {//不存在轉(zhuǎn)義字符,即需要作為參數(shù)進(jìn)行處理
                        expression.append(src, offset, end - offset);
                        offset = end + closeToken.length();
                        break;
                    }
                }
                if (end == -1) {
                    // close token was not found.
                    builder.append(src, start, src.length - start);
                    offset = src.length;
                } else {
                    //首先根據(jù)參數(shù)的key(即expression)進(jìn)行參數(shù)處理,返回?作為占位符
                    builder.append(handler.handleToken(expression.toString()));
                    offset = end + closeToken.length();
                }
            }
            start = text.indexOf(openToken, offset);
        }
        if (offset < src.length) {
            builder.append(src, offset, src.length - offset);
        }
        return builder.toString();
    }
}
ParameterMapping

(MyBatis源碼中粘貼)

package com.zx.utils;

public class ParameterMapping {

    private String content;

    public ParameterMapping(String content) {
        this.content = content;
    }
    // getter... setter...
}

ParameterMappingTokenHandler

(MyBatis源碼中粘貼)

package com.zx.utils;

import java.util.ArrayList;
import java.util.List;

public class ParameterMappingTokenHandler implements TokenHandler {
    private List<ParameterMapping> parameterMappings = new ArrayList<ParameterMapping>();

    // context是參數(shù)名稱 #{id} #{username}
    public String handleToken(String content) {
        parameterMappings.add(buildParameterMapping(content));
        return "?";
    }

    private ParameterMapping buildParameterMapping(String content) {
        ParameterMapping parameterMapping = new ParameterMapping(content);
        return parameterMapping;
    }
    // getter... setter...
}
TokenHandler

(MyBatis源碼中粘貼)

package com.zx.utils;

public interface TokenHandler {
  String handleToken(String content);
}

自定義持久層框架優(yōu)化

問(wèn)題

  1. Dao層使用自定義持久層框架,存在代碼重復(fù),整個(gè)操作的過(guò)程重復(fù)(加載配置文件、創(chuàng)建sqlSessionFactory、生產(chǎn)sqlSession)
  2. statementId存在硬編碼

解決方案

使用代理模式生成Dao層的代理實(shí)現(xiàn)類

代碼實(shí)現(xiàn)

SqlSession中新增
/**
* 為Dao接口生成動(dòng)態(tài)代理
* @param mapperClass
* @param <T>
* @return
*/
public <T> T getMapper(Class<?> mapperClass);
DefaultSqlSession中新增
@Override
public <T> T getMapper(Class<?> mapperClass) {
    // 使用JDK動(dòng)態(tài)代理來(lái)為Dao接口生成動(dòng)態(tài)代理對(duì)象,并返回
    Object proxyInstance = Proxy.newProxyInstance(DefaultSqlSession.class.getClassLoader(), new Class[]{mapperClass}, new InvocationHandler() {
        /**
        * 底層都是去執(zhí)行JDBC代碼
        * 根據(jù)不同情況來(lái)調(diào)用selectList或者selectOne
        * @param proxy:當(dāng)前代理對(duì)象的引用
        * @param method:當(dāng)前被調(diào)用方法的引用
        * @param args:傳遞的參數(shù)
        * @return
        * @throws Throwable
        */
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            // 準(zhǔn)備參數(shù) 1:statementId:sql的唯一標(biāo)識(shí):namespace.id = 接口的全限定名.方法名
            // 方法名 findAll
            String methodName = method.getName();
            // 全限定名 com.zx.pojo.User
            String className = method.getDeclaringClass().getName();
            String statementId = className + "." + methodName;
            // 準(zhǔn)備參數(shù) 2:params:就是args
            // 獲取被調(diào)用方法的返回值類型
            Type genericReturnType = method.getGenericReturnType();
            // 判斷是否進(jìn)行了范型類型參數(shù)化
            if (genericReturnType instanceof ParameterizedType) {
                return selectList(statementId, args);
            }
            return selectOne(statementId, args);
        }
    });
    return (T) proxyInstance;
}

以上就是一個(gè)簡(jiǎn)單功能的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)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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