mybatis框架(01)

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

一、框架原理
sqlMapConfig.xml:(是mybatis的全局配置文件,名称不固定的)配置了数据源、事务等mybatis运行环境
mapper.xml:配置sql语句
SqlSessionFactory:(会话工厂),根据配置文件创建工厂作用:创建SqlSession
SqlSession(会话),是一个接口,面向用户(程序员)的接口作用:操作数据库(发出sql增、删、改、查)
Executor(执行器),是一个接口(基本执行器、缓存执行器)作用:SqlSession内部通过执行器操作数据库
mapped statement(底层封装对象)作用:对操作数据库存储封装,包括 sql语句,输入参数、输出结果类型。

二、传统JDBC开发

// 数据库连接
        Connection connection = null;
        // 预编译的Statement,使用预编译的Statement提高数据库性能
        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, "xx");
            // 向数据库发出sql执行查询,查询出结果集
            resultSet = preparedStatement.executeQuery();
            // 遍历查询结果集
            while (resultSet.next()) {
                System.out.println(resultSet.getString("id") + "  "
                        + resultSet.getString("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();
                }
            }

        }

这段代码中充斥着硬编码。
存在的问题大概分为这么几种:
第一:对数据连接对象的使用,需要的时候就用,不需要的时候就关闭,这种频繁的操作数据库连接是一件很浪费资源的事情。
第二:sql语句编写在java代码中,当后期需要维护和修改sql那么这个.java文件需要重新编译。维护成本很高
第三:preparedStatement中设置参数,对占位符号位置和设置参数值,硬编码在java代码中,不利于系统维护。
第四:遍历结果集,我相信使用过结果集的人,会对这边的情况很是头疼尤其是查询的字段很多的时候,一不留神字符串写错,那么数据就取不到了。

转载于:https://my.oschina.net/u/3046510/blog/791675

你可能感兴趣的:(java,数据库,python)