mybatis框架(01)

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

2、传统JDBC开发mysql

// 数据库链接
        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代码中,不利于系统维护。
第四:遍历结果集,我相信使用过结果集的人,会对这边的状况非常头疼尤为是查询的字段不少的时候,一不留神字符串写错,那么数据就取不到了。程序员

相关文章
相关标签/搜索