mybatis学习笔记

本文探讨了使用JDBC编程存在的问题,并介绍了如何通过MyBatis框架解决这些问题。包括利用数据库连接池优化连接管理、将SQL语句配置在XML文件中以便维护、通过XML配置参数映射以及实现结果集自动映射成Java对象等功能。

jdbc程序

public static void main(String[] args) {
        Connection connection = null;//数据库连接
        PreparedStatement preparedStatement = null;//预编译的Statement
        ResultSet resultSet = null;//结果集
        try {
            // 加载驱动
            Class.forName("com.mysql.jdbc.Driver");
            // 创建连接
            connection = (Connection) DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/mybatis_day01?characterEncoding=utf-8", "root", "176166");
            // 定义sql语句
            String sql = "select * from user where username=?";
            preparedStatement = (PreparedStatement) connection.prepareStatement(sql);
            preparedStatement.setString(1, "joan");
            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) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if(preparedStatement!=null) {
                try {
                    preparedStatement.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if(connection!=null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

        }

    }

1 使用jdbc原生问题

  1 数据库频繁的链接开启和关闭,造成数据库资源浪费,影响数据库性能

  设想:使用数据库连接池管理数据库连接

  2 sql语句为硬编码到java代码中,不利于维护

  设想:将sql语句配置到xml文件中
  3 向preparedStatement中设置参数,设置占位符号位置,以及对应的参数值属于硬编码。
  设想:将sql语句及占位符和全部参数配置在xml中

  4 从resultSet中遍历结果集数据时存在硬编码
  设想:将查询结果集,自动映射成java对象

2 mybatis 框架

 mybatis是一个持久层的框架。让程序将主要精力放在sql上,通过mybatis提供的映射方式,自由灵活生成(半自动化,大部分需要程序员编写sql)满足需要的sql语句。向prepaerdStatement中的输入参数自动进行输入映射,将结果集映射成java对象(输出映射

 

 

  

  

转载于:https://www.cnblogs.com/joan-HTY/p/9012693.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值