(干货)老大:你为什么要用Mybatis,JDBC存在哪些问题?

1,005 阅读2分钟

文章目录

(一)jdbc查询代码

下面这段jdbc查询的代码,想必每个学过javaweb的同学,都是经历过的。

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", "123456");
            // 定义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、通过驱动管理类获取数据链接;
  • 3、自定义sql语句;
  • 4、拿到sql语句,并执行;
  • 5、拿到执行结果。

(二)JDBC存在的问题:

  • 1、数据库配置信息、sql执行语句等,写死在Java代码中(存在硬编码,不方便后期维护);
  • 2、每一次执行sql都会创建一个链接,并释放(浪费资源);
  • 3、对最终执行的结果需要手动的去封装返回结果集,较为繁琐。

(三)解决方案:

  • 1、使用配置文件加载配置信息;
  • 2、使用连接池,资源不用了就放回去,等待下一个使用的人;
  • 3、可以使用反射,对表的字段和Java实体类的属性做自动映射。
  • 4、使用其他持久层框架,例如:Mybatis