自定义持久层框架的代码实现二

Terwer MyBatis 后端开发评论356字数 3814阅读12分42秒阅读模式
摘要

本文实现了一个简单的MyBatis框架,包括数据库连接、SQL语句解析、参数设置、结果封装等功能。具体实现包括配置文件加载、Mapper接口与SQL语句映射、动态SQL处理、连接池管理等。通过这个框架可以简化数据库操作,提高开发效率。

代码实现续

核心执行引擎 Executor 的实现

/**
 * 执行器的实现
 *
 * @name: SimpleExecutor
 * @author: terwer
 * @date: 2022-03-14 16:53
 **/
public class SimpleExecutor implements Executor {
    @Override
    public <E> List<E> query(Configuration configuration, MappedStatement mappedStatement, Object... params) throws Exception {
        // 注册驱动,获取链接
        Connection connection = configuration.getDataSource().getConnection();

        // 获取sql语句
        // 获取的sql
        // select * from user where id = #{id} and username = #{username}
        // 转换后的sql
        // select * from user where id = ? and username = ?
        String sql = mappedStatement.getSql();

        // 转换sql语句
        BoundSql boundSql = getBoundSql(sql);

        // 获取预处理对象
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());

        // 设置参数
        // 参数全路径
        String parameterType = mappedStatement.getParameterType();
        Class<?> parameterClass = getClassType(parameterType);

        List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
        for (int i = 0; i < parameterMappingList.size(); i++) {
            ParameterMapping parameterMapping = parameterMappingList.get(i);
            String content = parameterMapping.getContent();

            Field field = parameterClass.getDeclaredField(content);
            field.setAccessible(true);
            Object value = field.get(params[0]);

            preparedStatement.setObject(i + 1, value);
        }

        // 执行sql
        ResultSet resultSet = preparedStatement.executeQuery();
        String returnType = mappedStatement.getResultType();
        Class<?> resultTypeClass = getClassType(returnType);
        Object o = resultTypeClass.newInstance();
        ArrayList<Object> objects = new ArrayList<>();

        // 封装返回结果集
        while (resultSet.next()) {
            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 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 tokenHandler = new ParameterMappingTokenHandler();
        GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", tokenHandler);

        // 解析后的sql
        String parseSql = genericTokenParser.parse(sql);
        // 解析的参数名称
        List<ParameterMapping> parameterMappings = tokenHandler.getParameterMappings();

        BoundSql boundSql = new BoundSql(parseSql, parameterMappings);

        return boundSql;
    }
}

运行效果文章源自浅海拾贝-https://blog.terwergreen.com/customize-the-code-implementation-of-the-long-lasting-layer-framework-two-zccchu.html

自定义持久层框架的代码实现二文章源自浅海拾贝-https://blog.terwergreen.com/customize-the-code-implementation-of-the-long-lasting-layer-framework-two-zccchu.html

问题修复

1、selectList 打印的全部是同一个值文章源自浅海拾贝-https://blog.terwergreen.com/customize-the-code-implementation-of-the-long-lasting-layer-framework-two-zccchu.html

/Library/Java/JavaVirtualMachines/jdk1.8.0_291.jdk/Contents/Home/bin/java -... com.intellij.rt.junit.JUnitStarter -ideVersion5 -junit4 com.terwergreen.test.IPersistenceTest,test2
Connected to the target VM, address: '127.0.0.1:50317', transport: 'socket'
log4j:WARN No appenders could be found for logger (com.mchange.v2.log.MLog).
log4j:WARN Please initialize the log4j system properly.
User{id=5, username='dali'}
User{id=5, username='dali'}
User{id=5, username='dali'}
User{id=5, username='dali'}
Disconnected from the target VM, address: '127.0.0.1:50317', transport: 'socket'

Process finished with exit code 0

修正方案文章源自浅海拾贝-https://blog.terwergreen.com/customize-the-code-implementation-of-the-long-lasting-layer-framework-two-zccchu.html

自定义持久层框架的代码实现二文章源自浅海拾贝-https://blog.terwergreen.com/customize-the-code-implementation-of-the-long-lasting-layer-framework-two-zccchu.html

修正后文章源自浅海拾贝-https://blog.terwergreen.com/customize-the-code-implementation-of-the-long-lasting-layer-framework-two-zccchu.html

/Library/Java/JavaVirtualMachines/jdk1.8.0_291.jdk/Contents/Home/bin/java -... com.intellij.rt.junit.JUnitStarter -ideVersion5 -junit4 com.terwergreen.test.IPersistenceTest,test2
Connected to the target VM, address: '127.0.0.1:50820', transport: 'socket'
log4j:WARN No appenders could be found for logger (com.mchange.v2.log.MLog).
log4j:WARN Please initialize the log4j system properly.
User{id=1, username='tyw'}
User{id=2, username='张月'}
User{id=4, username='haha'}
User{id=5, username='dali'}
Disconnected from the target VM, address: '127.0.0.1:50820', transport: 'socket'

Process finished with exit code 0

代码仓库

custom-persistence文章源自浅海拾贝-https://blog.terwergreen.com/customize-the-code-implementation-of-the-long-lasting-layer-framework-two-zccchu.html

文章更新历史文章源自浅海拾贝-https://blog.terwergreen.com/customize-the-code-implementation-of-the-long-lasting-layer-framework-two-zccchu.html

2024/04/24 同步文章到其他平台文章源自浅海拾贝-https://blog.terwergreen.com/customize-the-code-implementation-of-the-long-lasting-layer-framework-two-zccchu.html

2022/05/08 初稿 文章源自浅海拾贝-https://blog.terwergreen.com/customize-the-code-implementation-of-the-long-lasting-layer-framework-two-zccchu.html

文章源自浅海拾贝-https://blog.terwergreen.com/customize-the-code-implementation-of-the-long-lasting-layer-framework-two-zccchu.html

本文实现了一个简单的MyBatis框架,包括数据库连接、SQL语句解析、参数设置、结果封装等功能。具体实现包括配置文件加载、Mapper接口与SQL语句映射、动态SQL处理、连接池管理等。通过这个框架可以简化数据库操作,提高开发效率。文章源自浅海拾贝-https://blog.terwergreen.com/customize-the-code-implementation-of-the-long-lasting-layer-framework-two-zccchu.html

相关文章
  • 扫码加我微信
  • 验证消息请输入:来自你的博客
  • weinxin
  • 我的微信公众号
  • 微信扫一扫与我交流吧
  • weinxin
Terwer
匿名

发表评论

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: