阅读MyBaits源码困难?我们先手撕一个

文章内容输出来源:拉勾教育Java高薪训练营;

Spring学习笔记:https://blog.csdn.net/u011867674/article/details/108575248

SpringMVC:https://blog.csdn.net/u011867674/article/details/108709080

本篇文章是MyBatis学习课程中的一部分学习心得。

目录

1、分析JDBC操作问题

2、问题解决思路

3、自定义框架设计

4、自定义框架实现

使用端

框架端

5、自定义框架优化


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 user = new User();
                user.setId(id);
                user.setUsername(username);
            }
        } 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();
                }
            }
        }
    }

    这段代码我们最熟悉不过了,它是java操作数据库的必备步骤,但是我们在工程开发中基本上不会使用这种原生的JDBC来操作数据库了。为什么呢?我们分析下它存在的问题。

JDBC问题:

    1、数据库连接创建、释放频繁造成系统资源浪费,从而影响系统性能。

    2、Sql语句在代码中是硬编码,造成代码不易维护,实际应用中sql可能会频繁改动,那就需要修改java代码。

    3、使用preparedStatement向占位符传递参数存在硬编码,因为sql语句的where条件不确定,可能多也可能少,修改sql还要修改代码,系统不易维护。

    4、对结果集解析存在硬编码(查询列名),sql变化导致解析代码变化,系统不易维护,如果能将数据库记录封装成pojo对象解析比较方便。

 

2、问题解决思路

数据库频繁创建连接、释放资源:连接池

sql语句及参数硬编码:配置文件

手动解析封装返回结果集:反射、内省

 

3、自定义框架设计

使用端:

    提供核心配置文件

    sqlMapConfig.xml:存放数据源信息,引入mapper.xml

    Mapper.xml:sql语句的配置文件信息

框架端:

    1.读取配置文件

    读取完以后以流的形式存在,我们不能将读取到的配置信息以流的形式存放在内存中,不好操作,可以创建javaBean来存储

        (1)Configuration:存放数据库基本信息、Map<唯一标识,Mapper>  唯一标识:namespace+"."+id

        (2)MappedStatement:sql语句、statement类型、输入参数java类型、输出参数java类型

    2.解析配置文件

    创建SqlSessionFactoryBuilder类:

    方法:SqlSessionFactory build():

        (1)使用dom4j解析配置文件,将解析出来的内容封装到Configuration和MappedStatement中

        (2)创建SqlSessionFactory的实现类DefaultSqlSessionFactory

    3.编写SqlSessionFactory:

    方法:openSession():获取SqlSession接口的实现类实例对象

    4.创建SqlSession接口及实现类:主要封装CRUD方法

    方法:selectList(String statementId, Object... param):查询所有

              selectOne(String statementId, Object... param):查询单个

    5.创建Executor接口及实现类:真正执行JDBC的对象

    方法:query(Configuration configuration, MappedStatement mappedStatement, Object... params):执行jdbc,返回结果集

 

4、自定义框架实现

 

使用端

创建sqlMapConfig.xml


    
    
        
        
        
        
    

    
    

创建UserMapper.xml




    
    

    
    

User实体

public class User {

    private Integer id;

    private String username;

    getter、setter、toString...
}

IUserDao

public interface IUserDao {

    //查询所有用户
    List findAll() throws Exception;

    //根据条件进行用户查询
    User findByCondition(User user) throws Exception;

}

UserDaoImpl

public class UserDaoImpl implements IUserDao {
    @Override
    public List findAll() throws Exception {
        InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().bulid(resourceAsStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        List users = sqlSession.selectList("user.selectList");
        return users;
    }

    @Override
    public User findByCondition(User user) throws Exception {
        InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().bulid(resourceAsStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        return sqlSession.selectOne("user.selectOne", user);
    }
}

 

框架端

项目中配置下maven依赖

    
        UTF-8
        UTF-8
        1.8
        1.8
        1.8
    

    
        
            mysql
            mysql-connector-java
            5.1.17
        
        
            c3p0
            c3p0
            0.9.1.2
        
        
            log4j
            log4j
            1.2.12
        
        
            junit
            junit
            4.10
        
        
            dom4j
            dom4j
            1.6.1
        
        
            jaxen
            jaxen
            1.1.6
        
    

Configuration类

public class Configuration {

    private DataSource dataSource;

    /**
     * key: statementid(namespace+id)
     * value: 封装好的MappedStatement对象
     */
    private Map mappedStatementMap = new HashMap<>();

    getter、setter...
}

MappedStatement类

public class MappedStatement {

    /**
     * id标识
     */
    private String id;

    /**
     * 返回值类型
     */
    private String resultType;

    /**
     * 参数值类型
     */
    private String parameterType;

    /**
     * sql语句
     */
    private String sql;

    getter、setter... 
    
}

Resources

public class Resources {

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

}

SqlSessionFactoryBuilder

public class SqlSessionFactoryBuilder {

    public SqlSessionFactory bulid(InputStream in) throws Exception {
        // 第一: 使用dom4j解析配置文件,将解析出来的内容封装到Configuration中
        XMLConfigBuilder xmlConfigBuilder = new XMLConfigBuilder();
        Configuration configuration = xmlConfigBuilder.parseConfig(in);

        // 第二:创建SqlSessionFactory对象
        SqlSessionFactory sqlSessionFactory = new DefaultSqlSessionFactory(configuration);
        return sqlSessionFactory;
    }

}

XMLConfigBuilder

public class XMLConfigBuilder {

    private Configuration configuration;

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

    /**
     * 该方法就是使用dom4j对配置文件进行解析,封装Configuration
     * @param inputStream
     * @return
     */
    public Configuration parseConfig(InputStream inputStream) throws DocumentException, PropertyVetoException {

        Document document = new SAXReader().read(inputStream);
        // 
        Element rootElement = document.getRootElement();
        // dataSource相关配置
        List list = rootElement.selectNodes("//property");
        Properties properties = new Properties();
        for (Element element : list) {
            String name = element.attributeValue("name");
            String value = element.attributeValue("value");
            properties.put(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);

        List mapperList = rootElement.selectNodes("//mapper");

        for (Element element : mapperList) {
            String mapperXMLPath = element.attributeValue("resource");
            InputStream resourceAsStream = Resources.getResourceAsStream(mapperXMLPath);
            XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(configuration);
            xmlMapperBuilder.parse(resourceAsStream);
        }

        return configuration;
    }

}

XMLMapperBuilder

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 list = document.selectNodes("//select");
        for (Element element : list) {
            String id = element.attributeValue("id");
            String resultType = element.attributeValue("resultType");
            String paramterType = element.attributeValue("paramterType");
            String sql = element.getTextTrim();
            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setId(id);
            mappedStatement.setResultType(resultType);
            mappedStatement.setParameterType(paramterType);
            mappedStatement.setSql(sql);
            String key = namespace + "." + id;
            configuration.getMappedStatementMap().put(key, mappedStatement);
        }
    }

}

SqlSessionFactory

public interface SqlSessionFactory {

    SqlSession openSession();

}

DefaultSqlSessionFactory

public class DefaultSqlSessionFactory implements SqlSessionFactory {

    private Configuration configuration;

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

    @Override
    public SqlSession openSession(){
        return new DefaultSqlSession(configuration);
    }

}

SqlSession

public interface SqlSession {

    /**
     * 查询所有
     */
     List selectList(String statementId, Object... params) throws Exception;

    /**
     * 根据条件查询单个
     */
     T selectOne(String statementId, Object... params) throws Exception;


}

DefaultSqlSession

public class DefaultSqlSession implements SqlSession {

    private Configuration configuration;

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

    @Override
    public  List selectList(String statementId, Object... params) throws Exception {
        //将要去完成对simpleExecutor里的query方法的调用
        Executor executor = new SimpleExecutor();
        return executor.query(configuration, configuration.getMappedStatementMap().get(statementId), params);
    }

    @Override
    public  T selectOne(String statementId, Object... params) throws Exception {
        List objects = selectList(statementId, params);
        if (objects.size() == 1){
            return (T) objects.get(0);
        }else {
            throw new RuntimeException("查询结果为空或者返回结果过多");
        }
    }
}

Executor

public interface Executor {

     List query(Configuration configuration, MappedStatement mappedStatement, Object... params) throws Exception;

}

SimpleExecutor

public class SimpleExecutor implements Executor {

    @Override
    public  List 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 parameterType = mappedStatement.getParameterType();
        Class parameterTypeClass = getClassType(parameterType);
        List parameterMappingList = boundSql.getParameterMappingList();
        for (int i = 0; i < parameterMappingList.size(); i++) {
            ParameterMapping parameterMapping = parameterMappingList.get(i);
            String content = parameterMapping.getContent();

            //反射
            Field declaredField = parameterTypeClass.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 objects = new ArrayList<>();

        // 6、封装返回结果集
        while (resultSet.next()){
            //元数据
            ResultSetMetaData metaData = resultSet.getMetaData();
            Object o = resultTypeClass.newInstance();
            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) objects;
    }

    private Class getClassType(String parameterType) throws ClassNotFoundException {
        if (parameterType != null){
            Class aClass = Class.forName(parameterType);
            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 parameterMappings = parameterMappingTokenHandler.getParameterMappings();
        //封装BoundSql
        BoundSql boundSql = new BoundSql(parseSql, parameterMappings);
        return boundSql;
    }

}

BoundSql

public class BoundSql {

    /**
     * 解析过后的sql
     */
    private String sqlText;

    private List parameterMappingList = new ArrayList<>();

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

    public String getSqlText() {
        return sqlText;
    }

    public void setSqlText(String sqlText) {
        this.sqlText = sqlText;
    }

    public List getParameterMappingList() {
        return parameterMappingList;
    }

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

5、自定义框架优化

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

问题如下:

    (1)dao的实现类中存在重复的代码,整个操作的过程模板重复(创建SqlSession,调用SqlSession方法)

    (2)dao的实现类中存在硬编码,调用SqlSession的方法时,参数statement的id硬编码

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

阅读MyBaits源码困难?我们先手撕一个_第1张图片

在SqlSession中添加方法

/**
 * 为Dao接口生成代理实现类
 */
 T getMapper(Class mapperClass);

实现类

    @Override
    public  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代码 //根据不同情况,来调用selectList或者selectOne
                // 准备参数 1:statementid: 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){
                    return selectList(statementId, args);
                }
                return selectOne(statementId, args);
            }
        });
        return (T) proxyInstance;
    }

完整代码:https://github.com/shanbaobin00/easy-persistence

我们通过手撕一个持久层框架就能在整体上对持久层框架有一定的认识,它也是MyBatis的一个雏形,我们理解了这个雏形之后再去观看MyBatis源码就游刃有余了。

最后说下我的个人情况,工作大概1年左右,工作在一家国企。整天CRUD,干杂活。

平时也很想提升自己,在拉勾教育上也囤了点课,上下班的时候看一看。

腾讯课堂的公开课也白嫖了不是,但是真正理解的也就一点半点。

曾经也想过报个班看看,但是什么XX教育都太贵了基本上是上万的级别。

后来遇到了拉勾训练营,这个性价比看起来还是不错的。简单跟着学了几天,对MyBatis的源码有了较为深刻认识,同时也找到了阅读源码的技巧。班主任和导师都很负责,有什么问题直接抛群里就能够解决。群里的学习气氛也很浓厚,同学之间也互相帮助。

总之如果想要整体提升自己的同学,我比较推荐这个拉勾训练营。

你可能感兴趣的:(MyBatis,java)