美文网首页MyBatis专题
持久层框架(一)自定义持久层框架

持久层框架(一)自定义持久层框架

作者: 烦远远 | 来源:发表于2021-12-14 15:13 被阅读0次

    文章内容来源:拉勾教育Java高薪训练营(侵权联系删除)

    1 JDBC 存在的问题分析

    public static void main(String[] args) {
         Connection connection = null;
         PreparedStatement preparedStatement = null;
         ResultSet resultSet = null;
         try {
             // 加载数据库驱动
             Class.forName("com.mysql.jdbc.Driver");
             // 通过驱动管理类获取数据库链接
             connection =DriverManager.getConnection("jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8", "root","root");
             // 定义sql语句?表示占位符
             String sql = "select * from user where username = ?";
             // 获取预处理statement
             preparedStatement = connection.prepareStatement(sql);
             // 设置参数,第⼀个参数为sql语句中参数的序号(从1开始),第⼆个参数为设置的参数值
            preparedStatement.setString(1, "tom");
             // 向数据库发出sql执⾏查询,查询出结果集
             resultSet = preparedStatement.executeQuery();
             // 遍历查询结果集
             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();
                 }
         } 
    }
    

    JDBC 问题总结:
    原始jdbc开发存在的问题如下:
    1、 数据库连接创建、释放频繁造成系统资源浪费,从⽽影响系统性能。
    2、 Sql语句在代码中硬编码,造成代码不易维护,实际应⽤中sql变化的可能较⼤,sql变动需要改变 java代码。
    3、 使⽤preparedStatement向占有位符号传参数存在硬编码,因为sql语句的where条件不⼀定,可能 多也可能
    少,修改sql还要修改代码,系统不易维护。
    4、 对结果集解析存在硬编码(查询列名),sql变化导致解析代码变化,系统不易维护,如果能将数据库记录封装成pojo对象解析比较方便。

    2 自定义持久层框架要解决的问题

    ①使用数据库连接池初始化连接资源。
    ②将sql语句抽取到xml配置⽂件中。
    ③使用反射、内省等底层技术,自动将实体与表进行属性与字段的自动映射。

    3 自定义持久层框架设计

    使用端
    提供核心配置文件:
    sqlMapConfig.xml : 存放数据源信息,引入mapper.xml。
    Mapper.xml : sql语句的配置文件信息,比如订单的mapper,商品的mapper。
    框架端
    1.读取配置文件:
    读取完成以后以流的形式存在,我们不能将读取到的配置信息以流的形式存放在内存中,不好操作,可以创建javaBean来存储
    (1)Configuration : 存放数据库基本信息、Map<唯⼀标识,Mapper> 唯⼀标识:namespace + "." + id
    (2)MappedStatement:sql语句、statement类型、输⼊参数java类型、输出参数java类型
    2.解析配置文件:
    创建sqlSessionFactoryBuilder类:
    方法:sqlSessionFactory build():
    第一:使用dom4j解析配置文件,将解析出来的内容封装到Configuration和MappedStatement中
    第二:创建SqlSessionFactory的实现类DefaultSqlSession
    3.创建SqlSessionFactory:
    方法:openSession() : 获取sqlSession接⼝的实现类实例对象
    4.创建sqlSession接口及实现类:主要封装crud方法:
    查询所有:selectList(String statementId,Object param)。
    查询单个:selectOne(String statementId,Object param)。
    具体实现:封装JDBC完成对数据库表的查询操作
    涉及到的设计模式:
    Builder构建者设计模式、工厂模式、代理模式。

    4 自定义持久层框架实现

    4.1使用端配置

    创建maven工程:mybatis-self-defined-test
    创建 sqlMapConfig.xml

    <configuration>
        <!--数据库配置信息-->
        <dataSource>
            <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
            <property name="jdbcUrl" value="jdbc:mysql:///lg?characterEncoding=UTF-8"></property>
            <property name="username" value="root"></property>
            <property name="password" value="admain"></property>
        </dataSource>
    
        <!--存放mapper.xml的全路径-->
        <mapper resource="UserMapper.xml"></mapper>
    </configuration>
    

    创建UserMapper.xml

    <mapper namespace="user">
        <select id="selectOne" paramterType="com.lagou.pojo.User"
                resultType="com.lagou.pojo.User">
            select * from user where id = #{id} and username =#{username}
        </select>
    
        <select id="selectList" resultType="com.lagou.pojo.User">
            select * from user
        </select>
    </mapper>
    

    创建实体类User.java

    package com.lagou.pojo;
    
    public class User {
        
        private Integer id;
        private String username;
        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;
        }
    
        @Override
        public String toString() {
            return "User{" +
                    "id=" + id +
                    ", username='" + username + '\'' +
                    '}';
        }
    }
    

    4.2 框架端容器对象定义

    创建另maven工程:创mybatis-self-defined
    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">
    
        <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>
    
        <modelVersion>4.0.0</modelVersion>
        <groupId>com.lagou</groupId>
        <artifactId>mybatis-self-defined</artifactId>
        <version>1.0-SNAPSHOT</version>
        <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>
         <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <version>1.18.4</version>
                <scope>provided</scope>
            </dependency>
        </dependencies>
    </project>
    

    Resources.java
    创建Resource类,创建静态方法方便调用,参数传入路径,根据路径返回字节输入流。(获取使用端创建的配置文件)。

    package com.lagou.io;
    
    import java.io.InputStream;
    
    public class Resources {
        // 根据配置文件的路径,将配置文件加载成字节输入流,存储在内存中
        public static InputStream getResourceAsSteam(String path){
            InputStream resourceAsStream = Resources.class.getClassLoader().getResourceAsStream(path);
            return  resourceAsStream;
        }
    }
    
    

    接下来创建两个容器对象:用来保存根据配置路径获取到的配置xml文件解析出来的数据源以及sql信息。

    1. Configuration.java

    保存解析出来的数据源信息,以及mappendStatement对象们的集合。以map的形式保存,key 是statemendId(mapper.xml里的nameSpace.id sql语句的唯一标识),value 就是封装好的mappedStatemend对象。

    package com.lagou.pojo;
    
    import lombok.Data;
    import javax.sql.DataSource;
    import java.util.HashMap;
    import java.util.Map;
    
    @Data
    public class Configuration {
    
        // 数据源对象
        private DataSource dataSource;
        
        // key: statementId(nameSpace.id sql的唯一标识)  value:封装好的mappedStatement对象
        Map<String,MappedStatement> mappedStatementMap = new HashMap<>();
        
    }
    

    2. MappedStatement.java

    映射配置类,存储mapper解析出来的内容,像sql语句,输入参数和输出参数等。

    package com.lagou.pojo;
    
    import lombok.Data;
    
    @Data
    public class MappedStatement {
        //id
        private String id;
        //sql语句
        private String sql;
        //输⼊参数
        private String paramterType;
        //输出参数
        private String resultType;
    
    }
    

    4.2 框架端dom4j解析配置文件封装到容器

    1. SqlSessionFactoryBuild.java
    此类完成了2个操作:
    第一:使用dom4j解析配置文件,将解析出来的xml的内容封装到Configuration中。
    第二:创建sqlSessionFactory对象:工厂类:生产sqlSession:会话对象。

    package com.lagou.sqlSession.Impl;
    
    import com.lagou.config.XMLConfigBuilder;
    import com.lagou.pojo.Configuration;
    import com.lagou.sqlSession.SqlSessionFactory;
    import org.dom4j.DocumentException;
    
    import java.beans.PropertyVetoException;
    import java.io.InputStream;
    
    public class SqlSessionFactoryBuild {
    
        public SqlSessionFactory build(InputStream in) throws DocumentException, PropertyVetoException {
    
            // 第一:使用dom4j解析配置文件,将解析出来的内容封装到Configuration中
            XMLConfigBuilder xmlConfigBuilder = new XMLConfigBuilder();
            Configuration configuration = xmlConfigBuilder.parseConfig(in);
    
            // 第二:创建sqlSessionFactory对象:工厂类:生产sqlSession:会话对象
            DefaultSqlSessionFactory defaultSqlSessionFactory = new DefaultSqlSessionFactory(configuration);
    
            return defaultSqlSessionFactory;
        }
    
    }
    

    XMLConfigBuilder 工具类对象封装实现了具体的解析配置文件的方法,返回Configuration对象。

    如图:使用段定义的sqlMapConfig.xml

    <configuration>
        <!--数据库配置信息-->
        <dataSource>
            <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
            <property name="jdbcUrl" value="jdbc:mysql:///lg"></property>
            <property name="username" value="root"></property>
            <property name="password" value="admain"></property>
        </dataSource>
    
        <!--存放mapper.xml的全路径-->
        <mapper resource="UserMapper.xml"></mapper>
    </configuration>
    

    XMLConfigBuilder.java

    将前面使用端定义好上图的sqlMapConfig.xml 对象解析出来 property 属性封装到c3p0数据池,构建数据源对象,构建到Configuration对象的dataSource属性。

    package com.lagou.config;
    
    import com.lagou.io.Resources;
    import com.lagou.pojo.Configuration;
    import com.mchange.v2.c3p0.ComboPooledDataSource;
    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对配置文件进行解析,封装Configuration
         */
        public Configuration parseConfig(InputStream inputStream) throws DocumentException, PropertyVetoException {
    
            Document document = new SAXReader().read(inputStream);
            //<configuration>
            Element rootElement = document.getRootElement();
            List<Element> list = rootElement.selectNodes("//property");
            Properties properties = new Properties();
            for (Element element : list) {
                String name = element.attributeValue("name");
                String value = element.attributeValue("value");
                properties.setProperty(name, value);
            }
    
            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);
            //mapper.xml解析: 拿到路径--字节输入流---dom4j进行解析
            List<Element> mapperList = rootElement.selectNodes("//mapper");
    
            for (Element element : mapperList) {
                String mapperPath = element.attributeValue("resource");
                InputStream resourceAsSteam = Resources.getResourceAsSteam(mapperPath);
                XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(configuration);
                xmlMapperBuilder.parse(resourceAsSteam);
            }
            return configuration;
        }
    
    }
    
    

    如图:使用段定义的userMapper.xml

    <mapper namespace="User">
        <select id="selectOne" paramterType="com.lagou.pojo.User"
                resultType="com.lagou.pojo.User">
            select * from user where id = #{id} and username =#{username}
        </select>
    
        <select id="selectList" resultType="com.lagou.pojo.User">
            select * from user
        </select>
    </mapper>
    

    将前面使用端定义好上图的userMapper.xml 对象解析出来 sql 的 属性封装到Map<String,MappedStatement>里面,构建到Configuration对象的mappedStatementMap属性。

    package com.lagou.config;
    
    import com.lagou.pojo.Configuration;
    import com.lagou.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("//select");
            for (Element element : list) {
                String id = element.attributeValue("id");
                String resultType = element.attributeValue("resultType");
                String paramterType = element.attributeValue("paramterType");
                String sqlText = element.getTextTrim();
                MappedStatement mappedStatement = new MappedStatement();
                mappedStatement.setId(id);
                mappedStatement.setResultType(resultType);
                mappedStatement.setParamterType(paramterType);
                mappedStatement.setSql(sqlText);
                String key = namespace+"."+id;
                configuration.getMappedStatementMap().put(key,mappedStatement);
    
            }
    
        }
        
    }
    
    

    4.3 创建sqlSessionFactory并生产sqlSession会话对象

    第一步解析pom文件,封装configuration对象完成后我们进行第二步,创建sqlSession对象(用到了工厂模式)。

    public class SqlSessionFactoryBuild {
    
        public SqlSessionFactory build(InputStream in) throws DocumentException, PropertyVetoException {
    
            // 第一:使用dom4j解析配置文件,将解析出来的内容封装到Configuration中
            XMLConfigBuilder xmlConfigBuilder = new XMLConfigBuilder();
            Configuration configuration = xmlConfigBuilder.parseConfig(in);
    
            // 第二:创建sqlSessionFactory对象:工厂类:生产sqlSession:会话对象
            DefaultSqlSessionFactory defaultSqlSessionFactory = new DefaultSqlSessionFactory(configuration);
            return defaultSqlSessionFactory;
        }
    }
    

    DefaultSqlSessionFactory .java

    DefaultSqlSessionFactory实现了SqlSessionFactory接口,openSession方法创建DefaultSession。
    我们将configuration向下传递,利用构造方法赋值给成员变量。

    package com.lagou.sqlSession.Impl;
    
    import com.lagou.pojo.Configuration;
    import com.lagou.sqlSession.SqlSession;
    import com.lagou.sqlSession.SqlSessionFactory;
    
    public class DefaultSqlSessionFactory implements SqlSessionFactory {
    
        private Configuration configuration;
    
        public DefaultSqlSessionFactory(Configuration configuration) {
            this.configuration = configuration;
        }
    
    
        @Override
        public SqlSession openSession() {
            return new DefaultSqlSession(configuration);
        }
    }
    

    SqlSession.java

    sqlSession接口里面定义了增删改查的方法。

    package com.lagou.sqlSession;
    
    import java.util.List;
    
    public interface SqlSession {
    
        //查询所有
        <E> List<E> selectList(String statementid, Object... params) throws Exception;
    
        //根据条件查询单个
        <T> T selectOne(String statementid, Object... params) throws Exception;
    
        //为Dao接口生成代理实现类
        <T> T getMapper(Class<?> mapperClass);
    
    
    }
    
    

    DefaultSqlSession.java
    DefaultSqlSession是sqlSession的实现类,是sqlsession的具体实现。
    里面实现了sqlSession定义的增删改查方法。

    package com.lagou.sqlSession.Impl;
    
    import com.lagou.pojo.Configuration;
    import com.lagou.pojo.MappedStatement;
    import com.lagou.sqlSession.SqlSession;
    
    import java.lang.reflect.*;
    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 {
    
            //将要去完成对simpleExecutor里的query方法的调用
            SimpleExecutor SimpleExecutor = new SimpleExecutor();
            MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementid);
            List<Object> list = SimpleExecutor.query(configuration, mappedStatement, params);
    
            return (List<E>) 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("查询结果为空或者返回结果过多");
            }
    
    
        }
    
        @Override
        public <T> T getMapper(Class<?> mapperClass) {
            // 使用JDK动态代理来为Dao接口生成代理对象,并返回
    
            Object proxyInstance = Proxy.newProxyInstance(DefaultSqlSession.class.getClassLoader(), new Class[]{mapperClass}, new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    // 底层都还是去执行JDBC代码 //根据不同情况,来调用selctList或者selectOne
                    // 准备参数 1:statmentid :sql语句的唯一标识:namespace.id= 接口全限定名.方法名
                    // 方法名:findAll
                    String methodName = method.getName();
                    String className = method.getDeclaringClass().getName();
    
                    String statementId = className + "." + methodName;
    
                    // 准备参数2:params:args
                    // 获取被调用方法的返回值类型
                    Type genericReturnType = method.getGenericReturnType();
                    // 判断是否进行了 泛型类型参数化
                    if (genericReturnType instanceof ParameterizedType) {
                        List<Object> objects = selectList(statementId, args);
                        return objects;
                    }
    
                    return selectOne(statementId, args);
    
                }
            });
            return (T) proxyInstance;
        }
    
    }
    
    

    4.4 创建Executor执行接口来封装对JDBC的操作

    Executor.java
    我们在Exector接口定义查询方法,返回值类型用泛型,参数有封装好的Configurator,mappedStatement 以及不确定的params类型。

    package com.lagou.sqlSession;
    
    import com.lagou.pojo.Configuration;
    import com.lagou.pojo.MappedStatement;
    
    import java.util.List;
    
    public interface Executor {
    
        <E> List<E> query(Configuration configuration, MappedStatement mappedStatement, Object... params) throws Exception;
    
    }
    

    SimpleExecutor .java

    SimpleExecutor实现的具体的JDBC方法
    第一步:获取数据库链接,我们根据传递进来的解析封装号的DataSource对象可以获取数据库链接。
    第二步:获取sql语句。
    sql语句存储在我们封装好的mappedStatement对象中。

    select * from user where id = #{id} and username =#{username}
    

    上图中,我们获取到的sql是用#{}这种格式所存储的。我们还需要将它转化为下图 jdbc 的格式,并且还要将#{}里面的字段名进行存储。

    select * from user where id = ? and username = ?
    

    下面是获得解析sql 的方法,因为我们还要对参数进行赋值,对#{}里面的字段名称我们也解析存储在了List<ParameterMapping> 中,并且将sql和参数列表封装在了BoundSql对象中。

    
        private BoundSql getBoundSql(String sql) {
            //标记处理类:配置标记解析器来完成对占位符的解析处理工作
            ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler();
            GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", parameterMappingTokenHandler);
            //解析出来的sql
            String parseSql = genericTokenParser.parse(sql);
            //#{}里面解析出来的参数名称
            List<ParameterMapping> parameterMappings = parameterMappingTokenHandler.getParameterMappings();
    
            BoundSql boundSql = new BoundSql(parseSql, parameterMappings);
            return boundSql;
    
        }
    

    BoundSql.java

    package com.lagou.config;
    
    import com.lagou.utils.ParameterMapping;
    import lombok.Data;
    
    import java.util.ArrayList;
    import java.util.List;
    
    @Data
    public class BoundSql {
    
        private String sqlText; //解析过后的sql
    
        private List<ParameterMapping> parameterMappingList = new ArrayList<>();
    
        public BoundSql(String sqlText, List<ParameterMapping> parameterMappingList) {
            this.sqlText = sqlText;
            this.parameterMappingList = parameterMappingList;
        }
        
    }
    
    

    第三步:获取预处理对象:preparedStatement

    PreparedStatement preparedStatement =connection.prepareStatement(boundSql.getSqlText());
    
    

    第四步:设置参数
    首先我们从传递进来的mappedStatement对象中可以拿到解析封装好的参数对象(User.java)的全路径(com.lagoupojo.user)。
    然后我们从解析到的sql的 #{} 中获取到了属性值的名称列表。
    我们循环获取到属性值然后通过反射获取到传递进来的对象(User)的属性值,然后将值存入预处理对象preparedStatement里面。

            // 获取参数类型的全路径
            String paramterType = mappedStatement.getParamterType();
            Class<?> paramtertypeClass = getClassType(paramterType);
    
            List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
            for (int i = 0; i < parameterMappingList.size(); i++) {
                // 获取解析到的#{}里里面的属性
                ParameterMapping parameterMapping = parameterMappingList.get(i);
                String content = parameterMapping.getContent();
                //反射 获取参数对象传递过来的值
                Field declaredField = paramtertypeClass.getDeclaredField(content);
                //暴力访问
                declaredField.setAccessible(true);
                Object o = declaredField.get(params[0]);
    
                preparedStatement.setObject(i + 1, o);
    
            }
    

    第五步:执行sql 获得返回结果

    ResultSet resultSet = preparedStatement.executeQuery();
    

    第六步:封装返回结果
    从mappedStatement获得返回值对象的全路径,然后通过反射获取到返回值对象,然后根据内省为其添加写入方法根据属性名写入属性值,然后将返回值对象添加进集合返回结果列表。

    String resultType = mappedStatement.getResultType();
    Class<?> resultTypeClass = getClassType(resultType);
    ArrayList<Object> objects = new ArrayList<>();
    while (resultSet.next()) {
          Object o = resultTypeClass.newInstance();
          //元数据
          ResultSetMetaData metaData = resultSet.getMetaData();
          for (int i = 1; i <= metaData.getColumnCount(); i++) {
           // 字段名
          String columnName = metaData.getColumnName(i);
          // 字段的值
          Object value = resultSet.getObject(columnName);
          //使用反射或者内省,根据数据库表和实体的对应关系,完成封装
          PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultTypeClass);
          Method writeMethod = propertyDescriptor.getWriteMethod();
          writeMethod.invoke(o, value);
          }
          objects.add(o);
    }
    

    下面是完整的具体的代码。

    package com.lagou.sqlSession.Impl;
    
    
    import com.lagou.config.BoundSql;
    import com.lagou.pojo.Configuration;
    import com.lagou.pojo.MappedStatement;
    import com.lagou.sqlSession.Executor;
    import com.lagou.utils.GenericTokenParser;
    import com.lagou.utils.ParameterMapping;
    import com.lagou.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                                                                                //user
        public <E> List<E> query(Configuration configuration, MappedStatement mappedStatement, Object... params) throws Exception {
            // 1. 注册驱动,获取连接
            Connection connection = configuration.getDataSource().getConnection();
    
            // 2. 获取sql语句 : select * from user where id = #{id} and username = #{username}
            //转换sql语句: select * from user where id = ? and username = ? ,转换的过程中,还需要对#{}里面的值进行解析存储
            String sql = mappedStatement.getSql();
            BoundSql boundSql = getBoundSql(sql);
    
            // 3.获取预处理对象:preparedStatement
            PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());
    
            // 4. 设置参数
            //获取到了参数的全路径
            String paramterType = mappedStatement.getParamterType();
            Class<?> paramtertypeClass = getClassType(paramterType);
    
            List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
            for (int i = 0; i < parameterMappingList.size(); i++) {
                // 获取解析到的#{}里里面的属性
                ParameterMapping parameterMapping = parameterMappingList.get(i);
                String content = parameterMapping.getContent();
                //反射 获取参数对象传递过来的值
                Field declaredField = paramtertypeClass.getDeclaredField(content);
                //暴力访问
                declaredField.setAccessible(true);
                Object o = declaredField.get(params[0]);
    
                preparedStatement.setObject(i + 1, o);
    
            }
    
    
            // 5. 执行sql
            ResultSet resultSet = preparedStatement.executeQuery();
            String resultType = mappedStatement.getResultType();
            Class<?> resultTypeClass = getClassType(resultType);
    
            ArrayList<Object> objects = new ArrayList<>();
    
            // 6. 封装返回结果集
            while (resultSet.next()) {
                Object o = resultTypeClass.newInstance();
                //元数据
                ResultSetMetaData metaData = resultSet.getMetaData();
                for (int i = 1; i <= metaData.getColumnCount(); i++) {
    
                    // 字段名
                    String columnName = metaData.getColumnName(i);
                    // 字段的值
                    Object value = resultSet.getObject(columnName);
    
                    //使用反射或者内省,根据数据库表和实体的对应关系,完成封装
                    PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultTypeClass);
                    Method writeMethod = propertyDescriptor.getWriteMethod();
                    writeMethod.invoke(o, value);
    
    
                }
                objects.add(o);
    
            }
            return (List<E>) objects;
    
        }
    
        private Class<?> getClassType(String paramterType) throws ClassNotFoundException {
            if (paramterType != null) {
                Class<?> aClass = Class.forName(paramterType);
                return aClass;
            }
            return null;
    
        }
    
    
        /**
         * 完成对#{}的解析工作:1.将#{}使用?进行代替,2.解析出#{}里面的值进行存储
         *
         * @param sql
         * @return
         */
        private BoundSql getBoundSql(String sql) {
            //标记处理类:配置标记解析器来完成对占位符的解析处理工作
            ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler();
            GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", parameterMappingTokenHandler);
            //解析出来的sql
            String parseSql = genericTokenParser.parse(sql);
            //#{}里面解析出来的参数名称
            List<ParameterMapping> parameterMappings = parameterMappingTokenHandler.getParameterMappings();
    
            BoundSql boundSql = new BoundSql(parseSql, parameterMappings);
            return boundSql;
    
        }
        
    }
    

    4.5 测试自定义持久层框架

    之前我们建立了mybatis-self-defined-test 工程,并且编写好了sqlMapConfig.xml和userMapper.xml文件。现在我们要将编写好的持久层框架引入进来使用。首先我们引入持久层框架的 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>
    
        <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>
    
        <groupId>com.lagou</groupId>
        <artifactId>mybatis-self-defined-test</artifactId>
        <version>1.0-SNAPSHOT</version>
    
        <dependencies>
            <dependency>
                <groupId>com.lagou</groupId>
                <artifactId>mybatis-self-defined</artifactId>
                <version>1.0-SNAPSHOT</version>
            </dependency>
        </dependencies>
        
    </project>
    

    然后编写测试类

    package com.lagou.test;
    
    import com.lagou.io.Resources;
    import com.lagou.pojo.User;
    import com.lagou.sqlSession.*;
    import com.lagou.sqlSession.Impl.SqlSessionFactoryBuilder;
    import org.junit.Test;
    
    import java.io.InputStream;
    
    public class TestQuery {
    
        @Test
        public void test() throws Exception {
            InputStream resourceAsSteam = Resources.getResourceAsSteam("sqlMapConfig.xml");
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsSteam);
            SqlSession sqlSession = sqlSessionFactory.openSession();
            //调用
            User userParam = new User();
            userParam.setId(1);
            userParam.setUsername("张三");
            User userResult = sqlSession.selectOne("user.selectOne", userParam);
            System.out.println(userResult.toString());
        }
    }
    

    运行测试类以后可以看到查出了结果集。


    运行结果

    5 通过代理模式优化自定义持久层框架

    5.1 自定义持久层框架的缺点

    public class UserDaoImpl implements IUserDao {
        @Override
        public List<User> selectList() throws Exception {
            InputStream resourceAsSteam = Resources.getResourceAsSteam("sqlMapConfig.xml");
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsSteam);
            SqlSession sqlSession = sqlSessionFactory.openSession();
            //调用
            User userParam = new User();
            userParam.setId(1);
            userParam.setUsername("张三");
            List<User> users = sqlSession.selectList("user.selectOne", userParam);
            return users;
        }
    
        @Override
        public User selectOne(User user) throws Exception {
            InputStream resourceAsSteam = Resources.getResourceAsSteam("sqlMapConfig.xml");
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsSteam);
            SqlSession sqlSession = sqlSessionFactory.openSession();
            //调用
            User userParam = new User();
            userParam.setUsername("张三");
            User userResult = sqlSession.selectOne("user.selectOne", userParam);
            return userResult;
        }
    }
    

    上述dao是西安类代码中有什么缺陷吗?
    1.代码重复,记载配置文件,获得sqlsession这段代码重复出现。
    2.存在硬编码,statementId存在硬编码问题。

    5.1 通过代理来实现Dao接口的具体实现

    上面我们分析了自定义持久层框架存在的问题,针对问题,要是Dao接口无需具体的实现类就不会有代码的重复以及硬编码问题了。我们可以通过sqlSession增加代理来实现Dao的具体实现。
    SqlSession .java

    public interface SqlSession {
    
        //查询所有
        <E> List<E> selectList(String statementid, Object... params) throws Exception;
    
        //根据条件查询单个
        <T> T selectOne(String statementid, Object... params) throws Exception;
    
        //为Dao接口生成代理实现类
        <T> T getMapper(Class<?> mapperClass);
    
    }
    

    DefaultSqlSession .java
    如下通过代理生成代理对象。
    根据参数和返回值通过结果的反射去执行不同的方法。之前我们将mapper接口的类路径和方法名和mapper中xml中的namespace和id分别做了对应,那我们就可以通过反射获取到类路径和方法名,获得statemendId。
    就可以去执行具体的JDBC方法了。

    public class DefaultSqlSession implements SqlSession {
     @Override
        public <T> T getMapper(Class<?> mapperClass) {
            // 使用JDK动态代理来为Dao接口生成代理对象,并返回
    
            Object proxyInstance = Proxy.newProxyInstance(DefaultSqlSession.class.getClassLoader(), new Class[]{mapperClass}, new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    // 底层都还是去执行JDBC代码 //根据不同情况,来调用selctList或者selectOne
                    // 准备参数 1:statmentid :sql语句的唯一标识:namespace.id= 接口全限定名.方法名
                    // 方法名:findAll
                    String methodName = method.getName();
                    String className = method.getDeclaringClass().getName();
    
                    String statementId = className + "." + methodName;
    
                    // 准备参数2:params:args
                    // 获取被调用方法的返回值类型
                    Type genericReturnType = method.getGenericReturnType();
                    // 判断是否进行了 泛型类型参数化
                    if (genericReturnType instanceof ParameterizedType) {
                        List<Object> objects = selectList(statementId, args);
                        return objects;
                    }
    
                    return selectOne(statementId, args);
    
                }
            });
            return (T) proxyInstance;
        }
    }
    

    相关文章

      网友评论

        本文标题:持久层框架(一)自定义持久层框架

        本文链接:https://www.haomeiwen.com/subject/viyyxrtx.html