wangwang
wangwang
文章32
标签32
分类5
MyBatis学习笔记一

MyBatis学习笔记一

一.原始JDBC连接实现

1.pom.xml添加mysql驱动依赖


<dependencys>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.48</version>
    </dependency>
    <!--lombok依赖,自动生成set,get方法-->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.22</version>
        <scope>compile</scope>
    </dependency>
</dependencys>

2.编写代码

执行类: JdbcConnect

public class JdbcConnect {

    public static void main(String[] args) {

        User user = new User();

        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        Connection connection = null;

        try {
            // 1.加载数据库驱动
            Class.forName("com.mysql.jdbc.Driver");
            // 2.获取连接配置,进行连接
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8&useSSL=false", "root", "root");
            // 3.获取执行的SQL语句
            String sql = "select * from user where username = ?";
            preparedStatement = connection.prepareStatement(sql);
            // 4.设置占位符的值,执行查询
            preparedStatement.setString(1, "测试");
            resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
                // 5.处理结果集映射
                int id = resultSet.getInt("id");
                String username = resultSet.getString("username");
                user.setId(id);
                user.setUserName(username);
            }
            System.out.println(user);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 6.资源关闭
            if (null != resultSet) {
                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();
                }

            }
        }

    }
}

实体类: User


@Data
public class User {

    private Integer id;

    private String userName;
}

3.JDBC问题总结

  • 数据库连接创建,释放频繁,浪费系统资源
  • SQL语句硬编码
  • SQL参数设置存在硬编码
  • 结果解析存在硬编码
本文作者:wangwang
本文链接:https://www.wangwangit.com/Mybatis%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0%E4%B8%80/
版权声明:本文采用 CC BY-NC-SA 3.0 CN 协议进行许可