二、手写MyBatis简易版框架

前言

今天准备自己动手写一个简易的MyBatis用来实现对数据库的操作。其实,Mybatis本质上是对JDBC进行了封装,然后使用各种优化来解决针对使用JDBC的一些痛点问题。温故而知新,先简单的回顾一下JDBC操作数据库的流程,然后思考一下JDBC这样使用的缺点。

回顾JDBC操作数据库

JDBC操作数据库流程

JDBC API 允许应用程序访问任何形式的表格数据,特别是存储在关系数据库中的数据。
image-20210812103601952.png

代码示例:

@Test
public void testJDBC() {
    Connection connection = null;
    PreparedStatement preparedStatement = null;
    ResultSet resultSet = null;

    try {
        // 1、加载数据库驱动
        Class.forName("com.mysql.cj.jdbc.Driver");
        // 2、通过驱动管理类获取数据库连接
        connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mybatis", "root", "root");
        // 3、定义sql语句?表示占位符
        String sql = "select * from t_user where username = ?";
        // 4、获取预处理statement
        preparedStatement = connection.prepareStatement(sql);
        // 5、 设置参数,第一个参数为sql语句中参数的序号(从1开始),第二个参数为设置的参数值
        preparedStatement.setString(1, "夜不收");
        // 6、向数据库发出sql执行查询,查询出结果集
        resultSet = preparedStatement.executeQuery();
        // 7、遍历查询结果集
        User user = new User();
        while (resultSet.next()) {
            int id = resultSet.getInt("id");
            String username = resultSet.getString("username");
            String password = resultSet.getString("password");
            int age = resultSet.getInt("age");
            String sex = resultSet.getString("sex");
            String email = resultSet.getString("email");
            // 封装User
            user.setId(id);
            user.setUsername(username);
            user.setPassword(password);
            user.setAge(age);
            user.setSex(sex);
            user.setEmail(email);
        }
        System.out.println(user);

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        // 8、释放资源
        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();
            }
        }
    }
}

JDBC问题分析&解决思路

针对上述JDBC操作数据的步骤,我们逐个分析。

  • 加载驱动,获取链接

image.png
存在问题1:数据库配置信息存在硬编码问题。优化思路:使用配置文件。
存在问题2:频繁创建、释放数据库连接问题。优化思路:使用数据连接池

  • 定义sql、设置参数、执行查询

image.png
存在问题3:SQL语句、设置参数、获取结果集参数均存在硬编码问题。优化思路:使用配置文件。

  • 遍历查询结果集

image.png
存在问题4:手动封装返回结果集,较为繁琐。优化思路:手动封装返回结果集,较为繁琐。

  • 问题总结

针对JDBC各个环节中存在的不足,我们整理出对应的优化思路,统一汇总:

存在问题优化思路
数据库配置信息存在硬编码问题使用配置文件
频繁创建、释放数据库连接问题使用数据连接池
SQL语句、设置参数、获取结果集参数均存在硬编码问题使用配置文件
手动封装返回结果集,较为繁琐使用Java反射

自定义持久层框架

思路分析

JDBC是个人作战,凡事亲力亲为,低效而高险,自己加载驱动,自己建连接,自己 …
而持久层框架好比是多工种协作,分工明确,执行高效,有专门负责解析注册驱动建立连接的,有专门管理数据连接池的,有专门执行sql语句的,有专门做预处理参数的,有专门装配结果集的 …

优化思路:框架的作用,就是为了帮助我们减去繁重开发细节与冗余代码,使我们能更加专注于业务应用开发。

使用JDBC和使用持久层框架区别

对比.jpg
是不是发现,拥有这么一套持久层框架是如此舒适,我们仅仅需要干两件事:

  • 配置数据源(地址/数据名/用户名/密码)
  • 编写SQL与参数准备(SQL语句/参数类型/返回值类型)

框架,除了思考本身的工程设计,还需要考虑到实际项目端的使用场景,干系方涉及两端:

  • 使用端(实际项目)
  • 持久层框架本身

以上两步,我们通过一张架构图《 手写持久层框架基本思路 》来梳理清楚:
3.jpg

核心接口/类重点说明

分工协作角色定位类名定义
负责读取配置文件资源辅助类Resources
负责存储数据库连接信息数据库资源类Configuration
负责存储SQL映射定义、存储结果集映射定义SQL与结果集资源类MappedStatement
负责解析配置文件,创建会话工厂SqlSessionFactory会话工厂构建者SqlSessionFactoryBuilder
负责创建会话SqlSession会话工厂SqlSessionFactory
指派执行器Executor会话SqlSession
负责执行SQL (配合指定资源Mapped Statement)执行器Executor

正常来说项目只对应一套数据库环境,一般对应一个SqlSessionFactory实例对象,我们使用单例模式只创建一个SqlSessionFactory实例。
如果需要配置多套数据库环境,那需要做一些拓展,例如Mybatis中通过environments等配置就可以支持多套测试/生产数据库环境进行切换。

项目使用端

  1. 调用框架API,除了引入自定义持久层框架的jar包。
  2. 提供两部分配置信息。
    1. mybatis-config.xml:数据库配置信息(地址/数据名/用户名/密码),以及mapper.xml的全路经。
    2. mapper.xml : SQL配置信息,存放SQL语句、参数类型、返回值类型相关信息。

自定义框架本身

  1. 加载配置文件:根据配置文件的路径,加载配置文件成字节输入流,存储在内存中。

image-20210811180809813.png

  1. 创建两个javaBean(容器对象):存放配置文件解析出来的内容。

image-20210811180923884.png

  1. 解析配置文件(使用dom4j),并创建SqlSession会话对象。

image-20210811180948093.png

  1. 创建SqlSessionFactory接口以及实现类DefaultSqlSessionFactory。

image-20210811181025728.png

  1. 创建SqlSession接口以及实现类DefaultSqlSession。

image-20210811181045390.png

  1. 创建Executor接口以及实现类SimpleExecutor。

image-20210811181106435.png

基本过程我们已经清晰,我们再细化一下类图,更好的助于我们实际编码:
4.jpg

最终手写的持久层框架结构参考

自定义框架部分:
image.png
项目使用端:
image.png

编码

在使用端项目中创建配置配置文件
创建 mybatis-config.xml

<configuration>

  <!--1.配置数据库信息-->
  <dataSource>
    <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
    <property name="url"
      value="jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8&amp;allowPublicKeyRetrieval=true&amp;useSSL=false&amp;serverTimezone=Asia/Shanghai"></property>
    <property name="username" value="root"></property>
    <property name="password" value="root"></property>
  </dataSource>

  <!--2.引入映射配置文件-->
  <mappers>
    <mapper resource="com/aiz/mapper/UserMapper.xml"></mapper>
  </mappers>

</configuration>

mapper.xml

<mapper namespace="com.aiz.dao.IUserDao">

  <!--根据条件查询单个-->
  <select id="selectOne" resultType="com.aiz.pojo.User" parameterType="com.aiz.pojo.User">
    select * from t_user where id = #{id} and username = #{username}
  </select>

  <!--查询所有-->
  <select id="selectList" resultType="com.aiz.pojo.User">
    select * from t_user
  </select>
</mapper>

User实体

package com.aiz.pojo;

public class User {
    private Integer id;

    private String username;

    private String password;

    private Integer age;

    private String sex;

    private String email;

    public User() {
    }

    public User(Integer id, String username, String password, Integer age, String sex, String email) {
        this.id = id;
        this.username = username;
        this.password = password;
        this.age = age;
        this.sex = sex;
        this.email = email;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    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 Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", age=" + age +
                ", sex='" + sex + '\'' +
                ", email='" + email + '\'' +
                '}';
    }
}

再创建一个Maven子工程并且导入需要用到的依赖坐标。

<?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>org.aiz.mybatis</groupId>
    <artifactId>mini-mybatis-xml</artifactId>
    <version>1.0-SNAPSHOT</version>
    <description>手写精简mybatis,解析XML版</description>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

    <dependencies>
        <!-- mysql 依赖-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.32</version>
        </dependency>

        <!--junit 依赖-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <!--作用域测试范围-->
            <scope>test</scope>
        </dependency>

        <!--dom4j 依赖-->
        <dependency>
            <groupId>dom4j</groupId>
            <artifactId>dom4j</artifactId>
            <version>1.6.1</version>
        </dependency>

        <!--xpath 依赖-->
        <dependency>
            <groupId>jaxen</groupId>
            <artifactId>jaxen</artifactId>
            <version>2.0.0</version>
        </dependency>


        <!--druid连接池-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.16</version>
        </dependency>

        <!-- log日志 -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
    </dependencies>

</project>

Resources

package com.aiz.io;

import java.io.InputStream;

public class Resources {
    /**
     * 根据配置文件的路径,加载配置文件成字节输入流,存到内存中
     */
    public static InputStream getResourceAsStream(String path) {
        InputStream resourceAsStream = Resources.class.getClassLoader().getResourceAsStream(path);
        return resourceAsStream;
    }
}

Configuration

package com.aiz.pojo;

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

/**
 * 全局配置类:存放核心配置文件解析出来的内容
 */
public class Configuration {

    /**
     * 数据源对象
     */
    private DataSource dataSource;
    /**
     * key:statementId:namespace.id   MappedStatement:封装好的MappedStatement对象
     */
    private Map<String, MappedStatement> mappedStatementMap = new HashMap();

    public DataSource getDataSource() {
        return dataSource;
    }

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    public Map<String, MappedStatement> getMappedStatementMap() {
        return mappedStatementMap;
    }

    public void setMappedStatementMap(Map<String, MappedStatement> mappedStatementMap) {
        this.mappedStatementMap = mappedStatementMap;
    }
}

MappedStatement

package com.aiz.pojo;

/**
 * 映射配置类:存放mapper.xml解析内容
 */
public class MappedStatement {

    /**
     * 唯一标识 statementId:namespace.id
     */
    private String statementId;
    /**
     * 返回值类型
     */
    private String resultType;
    /**
     * 参数值类型
     */
    private String parameterType;
    /**
     * sql语句
     */
    private String sql;
    /**
     * sqlCommandType :判断当前是什么操作的一个属性
     */
    private String sqlCommandType;

    public String getSqlCommandType() {
        return sqlCommandType;
    }

    public void setSqlCommandType(String sqlCommandType) {
        this.sqlCommandType = sqlCommandType;
    }

    public String getStatementId() {
        return statementId;
    }

    public void setStatementId(String statementId) {
        this.statementId = statementId;
    }

    public String getResultType() {
        return resultType;
    }

    public void setResultType(String resultType) {
        this.resultType = resultType;
    }

    public String getParameterType() {
        return parameterType;
    }

    public void setParameterType(String parameterType) {
        this.parameterType = parameterType;
    }

    public String getSql() {
        return sql;
    }

    public void setSql(String sql) {
        this.sql = sql;
    }
}

SqlSessionFactoryBuilder

package com.aiz.session;

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

import java.io.InputStream;

public class SqlSessionFactoryBuilder {
    /**
     * 1.解析配置文件,封装容器对象。
     * 2.创建SqlSessionFactory工厂对象
     */
    public SqlSessionFactory build(InputStream inputStream) throws DocumentException {

        // 1.解析配置文件,封装容器对象 XMLConfigBuilder:专门解析核心配置文件的解析类
        XMLConfigBuilder xmlConfigBuilder = new XMLConfigBuilder();
        Configuration configuration =  xmlConfigBuilder.parse(inputStream);

        // 2.创建SqlSessionFactory工厂对象
        return new DefaultSqlSessionFactory(configuration);
    }
}

XMLConfigerBuilder

package com.aiz.config;

import com.aiz.io.Resources;
import com.aiz.pojo.Configuration;
import com.alibaba.druid.pool.DruidDataSource;
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;
import java.util.Properties;

public class XMLConfigBuilder {

    private Configuration configuration;

    public XMLConfigBuilder() {
        this.configuration = new Configuration();
    }

    /**
     * 使用dom4j+xpath解析配置文件,封装Configuration对象
     *
     * @param inputStream
     * @return
     */
    public Configuration parse(InputStream inputStream) throws DocumentException {

        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();

        List<Element> list = rootElement.selectNodes("//property");

        // <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
        Properties properties = new Properties();
        for (Element element : list) {
            String name = element.attributeValue("name");
            String value = element.attributeValue("value");
            properties.setProperty(name, value);
        }

        // 创建数据源对象
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName(properties.getProperty("driverClassName"));
        druidDataSource.setUrl(properties.getProperty("url"));
        druidDataSource.setUsername(properties.getProperty("username"));
        druidDataSource.setPassword(properties.getProperty("password"));

        // 创建好的数据源对象封装到Configuration对象中
        configuration.setDataSource(druidDataSource);

        //-----------解析映射配置文件----
        // 1.获取映射配置文件的路径 2.根据路径进行映射配置文件的加载解析 3.封装到MappedStatement--》configuration里面的map集合中
        // <mapper resource="com/aiz/mapper/UserMapper.xml"></mapper>
        List<Element> mapperList = rootElement.selectNodes("//mapper");
        for (Element element : mapperList) {
            String mapperPath = element.attributeValue("resource");
            InputStream resourceAsSteam = Resources.getResourceAsStream(mapperPath);
            // XMLMapperBuilder:专门解析映射配置文件的对象
            XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(configuration);
            xmlMapperBuilder.parse(resourceAsSteam);
        }
        return configuration;

    }
}

XMLMapperBuilder

package com.aiz.config;

import com.aiz.pojo.Configuration;
import com.aiz.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;

/**
 * parse : 解析映射配置文件 --> mappedStatement --> configuration里面的map集合中
 */
public class XMLMapperBuilder {

    private Configuration configuration;

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

    public void parse(InputStream resourceAsSteam) throws DocumentException {

        Document document = new SAXReader().read(resourceAsSteam);
        Element rootElement = document.getRootElement();

        /**
         *  <select id="selectOne" resultType="com.aiz.pojo.User" parameterType="com.aiz.pojo.User">
         *         select * from user where id = #{id} and username = #{username}
         *    </select>
         */
        List<Element> selectList = rootElement.selectNodes("//select");
        String namespace = rootElement.attributeValue("namespace");
        for (Element element : selectList) {

            String id = element.attributeValue("id");
            String resultType = element.attributeValue("resultType");
            String parameterType = element.attributeValue("parameterType");
            String sql = element.getTextTrim();

            // 封装mappedStatement对象
            MappedStatement mappedStatement = new MappedStatement();

            // StatementId:namespace.id
            String statementId = namespace + "." + id;
            mappedStatement.setStatementId(statementId);
            mappedStatement.setResultType(resultType);
            mappedStatement.setParameterType(parameterType);
            mappedStatement.setSql(sql);
            mappedStatement.setSqlCommandType("select");

            // 将封装好的mappedStatement封装到configuration中的map集合中
            configuration.getMappedStatementMap().put(statementId, mappedStatement);

        }

    }
}

sqlSessionFactory 接口及DefaultSqlSessionFactory 实现类

package com.aiz.session;


public interface SqlSessionFactory {

    /**
     * 1.生产sqlSession对象。
     * 2.创建执行器对象。
     */
    SqlSession openSession();
}

package com.aiz.session;

import com.aiz.executor.Executor;
import com.aiz.executor.SimpleExecutor;
import com.aiz.pojo.Configuration;

public class DefaultSqlSessionFactory implements SqlSessionFactory {

    private Configuration configuration;

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

    @Override
    public SqlSession openSession() {
        // 1.创建执行器对象
        Executor simpleExecutor = new SimpleExecutor();

        // 2.生产sqlSession对象
        DefaultSqlSession defaultSqlSession = new DefaultSqlSession(configuration, simpleExecutor);

        return defaultSqlSession;
    }
}

sqlSession 接口及 DefaultSqlSession 实现类

package com.aiz.session;

import java.util.List;

public interface SqlSession {
    /**
     * 查询多个结果
     * sqlSession.selectList(); :定位到要执行的sql语句,从而执行
     * select * from user where username like '% ? %'
     */
    <E> List<E> selectList(String statementId, Object param) throws Exception;

    /**
     * 查询单个结果
     */
    <T> T selectOne(String statementId, Object param) throws Exception;

    /**
     * 清除资源
     */
    void close();

    /**
     * 生成代理对象
     */
    <T> T getMapper(Class<?> mapperClass);
}

package com.aiz.session;

import com.aiz.executor.Executor;
import com.aiz.pojo.Configuration;
import com.aiz.pojo.MappedStatement;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Proxy;
import java.lang.reflect.Type;
import java.util.List;

public class DefaultSqlSession implements SqlSession {

    private Configuration configuration;
    private Executor executor;

    public DefaultSqlSession(Configuration configuration, Executor executor) {
        this.configuration = configuration;
        this.executor = executor;
    }

    @Override                                        // user
    public <E> List<E> selectList(String statementId, Object param) throws Exception {
        // 将查询操作委派给底层的执行器
        // query(): 执行底层的JDBC 1.数据库配置信息 2.sql配置信息
        MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementId);
        List<E> list = executor.query(configuration, mappedStatement, param);

        return list;
    }

    @Override
    public <T> T selectOne(String statementId, Object param) throws Exception {
        // 去调用selectList();
        List<Object> list = this.selectList(statementId, param);
        if (list.size() == 1) {
            return (T) list.get(0);
        } else if (list.size() > 1) {
            throw new RuntimeException("返回结果过多");
        } else {
            return null;
        }

    }
}

Executor

package com.aiz.executor;

import com.aiz.pojo.Configuration;
import com.aiz.pojo.MappedStatement;

import java.util.List;

public interface Executor {

    <E> List<E> query(Configuration configuration, MappedStatement mappedStatement, Object param) throws Exception;

    void close();
}

SimpleExecutor

package com.aiz.executor;

import com.aiz.config.BoundSql;
import com.aiz.pojo.Configuration;
import com.aiz.pojo.MappedStatement;
import com.aiz.utils.GenericTokenParser;
import com.aiz.utils.ParameterMapping;
import com.aiz.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.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class SimpleExecutor implements Executor {

    private Connection connection = null;
    private PreparedStatement preparedStatement = null;
    private ResultSet resultSet = null;

    @Override                                                                               // user
    public <E> List<E> query(Configuration configuration, MappedStatement mappedStatement, Object param) throws Exception {

        // 1.加载驱动,获取数据库连接
        connection = configuration.getDataSource().getConnection();

        // 2.获取preparedStatement预编译对象
        // 获取要执行的sql语句
        /*      自定义的占位符
                select * from user where id = #{id} and username = #{username}
         替换:  select * from user where id = ? and username = ?
                解析替换的过程中:#{id}里面的值保存下来
         */
        String sql = mappedStatement.getSql();
        BoundSql boundSql = getBoundSql(sql);
        String finalSql = boundSql.getFinalSql();
        preparedStatement = connection.prepareStatement(finalSql);

        // 3.设置参数
        // com.aiz.pojo.User
        String parameterType = mappedStatement.getParameterType();

        if (parameterType != null) {
            Class<?> parameterTypeClass = Class.forName(parameterType);

            List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
            for (int i = 0; i < parameterMappingList.size(); i++) {

                ParameterMapping parameterMapping = parameterMappingList.get(i);
                // id || username
                String paramName = parameterMapping.getContent();
                // 反射
                Field declaredField = parameterTypeClass.getDeclaredField(paramName);
                // 暴力访问
                declaredField.setAccessible(true);

                Object value = declaredField.get(param);
                // 赋值占位符
                preparedStatement.setObject(i + 1, value);
            }

        }

        // 4.执行sql,发起查询
        resultSet = preparedStatement.executeQuery();

        // 5.处理返回结果集
        ArrayList<E> list = new ArrayList<>();
        while (resultSet.next()) {
            // 元数据信息 包含了 字段名  字段的值
            ResultSetMetaData metaData = resultSet.getMetaData();

            // com.aiz.pojo.User
            String resultType = mappedStatement.getResultType();
            Class<?> resultTypeClass = Class.forName(resultType);
            Object o = resultTypeClass.newInstance();

            for (int i = 1; i <= metaData.getColumnCount(); i++) {

                // 字段名 id  username
                String columnName = metaData.getColumnName(i);
                // 字段的值
                Object value = resultSet.getObject(columnName);

                // 问题:现在要封装到哪一个实体中
                // 封装
                // 属性描述器:通过API方法获取某个属性的读写方法
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultTypeClass);
                Method writeMethod = propertyDescriptor.getWriteMethod();
                // 参数1:实例对象 参数2:要设置的值
                writeMethod.invoke(o, value);
            }
            list.add((E) o);

        }

        return list;
    }

    /**
     * 1.#{}占位符替换成?  2.解析替换的过程中 将#{}里面的值保存下来
     */
    private BoundSql getBoundSql(String sql) {

        // 1.创建标记处理器:配合标记解析器完成标记的处理解析工作
        ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler();
        // 2.创建标记解析器
        GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", parameterMappingTokenHandler);

        // #{}占位符替换成? 2.解析替换的过程中 将#{}里面的值保存下来 ParameterMapping
        String finalSql = genericTokenParser.parse(sql);

        // #{}里面的值的一个集合 id username
        List<ParameterMapping> parameterMappings = parameterMappingTokenHandler.getParameterMappings();

        BoundSql boundSql = new BoundSql(finalSql, parameterMappings);

        return boundSql;
    }


    /**
     * 释放资源
     */
    @Override
    public void close() {
        // 释放资源
        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();
            }
        }


    }
}

BoundSql

package com.aiz.config;

import com.aiz.utils.ParameterMapping;

import java.util.List;

public class BoundSql {

    private String finalSql;

    private List<ParameterMapping> parameterMappingList;

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

    public String getFinalSql() {
        return finalSql;
    }

    public void setFinalSql(String finalSql) {
        this.finalSql = finalSql;
    }

    public List<ParameterMapping> getParameterMappingList() {
        return parameterMappingList;
    }

    public void setParameterMappingList(List<ParameterMapping> parameterMappingList) {
        this.parameterMappingList = parameterMappingList;
    }
}

编码优化

通过上述我们的自定义框架,我们解决了JDBC操作数据库带来的一些问题:例如频繁创建释放数据库连 接,硬编码,手动封装返回结果集等问题,但是现在我们继续来分析刚刚完成的自定义框架代码,有没有什么问题?
问题如下:

  • dao的实现类中存在重复的代码,整个操作的过程模板重复(创建sqlsession,调用sqlsession方法,关闭 sqlsession)
  • dao的实现类中存在硬编码,调用sqlsession的方法时,参数statement的id硬编码。

解决:使用代理模式来创建接口的代理对象。

在sqlSession中添加方法

public interface SqlSession {
   public <T> T getMappper(Class<?> mapperClass);
}

实现类

package com.aiz.session;

import com.aiz.executor.Executor;
import com.aiz.pojo.Configuration;
import com.aiz.pojo.MappedStatement;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Proxy;
import java.lang.reflect.Type;
import java.util.List;

public class DefaultSqlSession implements SqlSession {

    private Configuration configuration;
    private Executor executor;

    public DefaultSqlSession(Configuration configuration, Executor executor) {
        this.configuration = configuration;
        this.executor = executor;
    }

    @Override
    public void close() {
        executor.close();
    }

    @SuppressWarnings("all")
    @Override
    public <T> T getMapper(Class<?> mapperClass) {

        // 使用JDK动态代理生成基于接口的代理对象
        Object proxy = Proxy.newProxyInstance(DefaultSqlSession.class.getClassLoader(), new Class[]{mapperClass}, new InvocationHandler() {
            /*
                Object:代理对象的引用,很少用
                Method:被调用的方法的字节码对象
                Object[]:调用的方法的参数
             */
            @Override
            public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
                // 具体的逻辑 :执行底层的JDBC
                // 通过调用sqlSession里面的方法来完成方法调用
                // 参数的准备:1.statementId: com.aiz.dao.IUserDao.findAll  2.param
                // 问题1:无法获取现有的statementId
                // findAll
                String methodName = method.getName();
                // com.aiz.dao.IUserDao
                String className = method.getDeclaringClass().getName();
                String statementId = className + "." + methodName;

                // 方法调用:问题2:要调用sqlSession中增删改查的什么方法呢?
                // 改造当前工程:sqlCommandType
                MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementId);
                // select  update delete insert
                String sqlCommandType = mappedStatement.getSqlCommandType();
                switch (sqlCommandType) {
                    case "select":
                        // 执行查询方法调用
                        // 问题3:该调用selectList还是selectOne?
                        Type genericReturnType = method.getGenericReturnType();
                        // 判断是否实现了 泛型类型参数化
                        if (genericReturnType instanceof ParameterizedType) {
                            if (objects != null) {
                                return selectList(statementId, objects[0]);
                            }
                            return selectList(statementId, null);
                        }
                        return selectOne(statementId, objects[0]);

                    case "update":
                        // 执行更新方法调用
                        break;
                    case "delete":
                        // 执行delete方法调用
                        break;
                    case "insert":
                        // 执行insert方法调用
                        break;

                }
                return null;
            }
        });
        return (T) proxy;
    }
}

使用端测试代码

package com.aiz.test;


import com.aiz.dao.IUserDao;
import com.aiz.io.Resources;
import com.aiz.pojo.User;
import com.aiz.session.SqlSession;
import com.aiz.session.SqlSessionFactory;
import com.aiz.session.SqlSessionFactoryBuilder;
import org.junit.Test;

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

public class MiniMybatisTest {

    /**
     * 传统方式(不使用mapper代理)测试
     */
    @Test
    public void test1() throws Exception {

        // 1.根据配置文件的路径,加载成字节输入流,存到内存中 注意:配置文件还未解析
        InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");

        // 2.解析了配置文件,封装了Configuration对象  2.创建sqlSessionFactory工厂对象
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);

        // 3.生产sqlSession 创建了执行器对象
        SqlSession sqlSession = sqlSessionFactory.openSession();

        // 4.调用sqlSession方法
        User user = new User();
        user.setId(1);
        user.setUsername("赵六");
        /*User user2 = sqlSession.selectOne("com.aiz.dao.IUserDao.findByCondition", user);
        System.out.println(user2);*/
        List<User> list = sqlSession.selectList("com.aiz.dao.IUserDao.findAll", null);
        for (User user1 : list) {
            System.out.println(user1);
        }

        // 5.释放资源
        sqlSession.close();
    }

    /**
     * mapper代理测试
     */
    @Test
    public void test2() throws Exception {

        // 1.根据配置文件的路径,加载成字节输入流,存到内存中 注意:配置文件还未解析
        InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");

        // 2.解析了配置文件,封装了Configuration对象  2.创建sqlSessionFactory工厂对象
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);

        // 3.生产sqlSession 创建了执行器对象
        SqlSession sqlSession = sqlSessionFactory.openSession();

        // 4.调用sqlSession方法
        IUserDao userDao = sqlSession.getMapper(IUserDao.class);

        /*User user1 = new User();
        user1.setId(1);
        user1.setUsername("赵六");
        User user3 = userDao.findByCondition(user1);
        System.out.println(user3);*/
        List<User> all = userDao.findAll();
        all.stream().forEach(System.out::println);

        // 5.释放资源
        sqlSession.close();
    }
}

参考资料

B站视频xml版+13小时手撕源码

GitHub代码地址!!!

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

耀耀zz

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值