为什么要使用Mybatis?

在使用Mybatis之前,是如何操作数据库进行curd的?

1.首先创建一张表,名称为t_person,建表语句如下所示:

CREATE TABLE `t_person` (
`id` BIGINT ( 20 ) NOT NULL COMMENT '主键',
`name` VARCHAR ( 20 ) NOT NULL COMMENT '名字',
`mobile` VARCHAR ( 30 ) NOT NULL COMMENT '手机号',
`age` INT ( 4 ) DEFAULT NULL COMMENT '年龄',
`create_at` datetime NOT NULL COMMENT '创建时间',
`update_at` datetime NOT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT '修改时间',
PRIMARY KEY ( `id` ) 
) ENGINE = INNODB DEFAULT CHARSET = utf8mb4;

2.java代码中定义表结构对象,Person实体类

@Data
public class Person {

    private Long id;

    private String name;

    private String mobile;

    private Integer age;

    private Date createAt;

    private Date updateAt;
    
}

3.java代码中编写DAO类对象,操作数据库

public class PersonDAO {

    private static final String url = "jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=UTF8&useSSL=false&serverTimezone=UTC";

    private static final String username = "root";

    private static final String password = "123456";

    private static DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    public Person selectById(Long id) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");

            // 获取链接
            connection = DriverManager.getConnection(url, username, password);

            // 创建statement
            preparedStatement = connection.prepareStatement("select * from t_person where id = ?");
            preparedStatement.setLong(1, id);

            // 执行
            resultSet = preparedStatement.executeQuery();

            // 遍历结果集
            Person person = null;
            while (resultSet.next()) {
                Long realId = resultSet.getLong("id");
                String name = resultSet.getString("name");
                String mobile = resultSet.getString("mobile");
                int age = resultSet.getInt("age");
                Date createAt = resultSet.getDate("create_at");
                Date updateAt = resultSet.getDate("update_at");
                person = new Person();
                person.setId(realId);
                person.setName(name);
                person.setMobile(mobile);
                person.setAge(age);
                person.setCreateAt(createAt);
                person.setUpdateAt(updateAt);
            }
            return person;
        } catch (Exception e) {
            return null;
        }finally {
            // 关闭资源
            try {
                if(connection!= null && !connection.isClosed())
                    connection.close();
                if(preparedStatement != null)
                    preparedStatement.close();
                if(resultSet != null)
                    resultSet.close();
            }catch (Exception e){
                
            }
        }
    }

}

4.数据库中插入一条记录



5.调用DAO方法查询结果

PersonDAO personDAO = new PersonDAO();
Person person = personDAO.selectById(3L);
System.out.println("person = " + person);
打印结果如下:
person = Person(id=3, name=张三, mobile=12233334444, age=18, createAt=2021-12-11, updateAt=2021-12-11)

流程梳理并总结

对于业务开发者而言,绿色部分标注的过程才是最核心的需求,而为了实现这一个需求,我们先要获取数据库链接,创建statement,拼接sql,遍历ResultSet,关闭资源等等,而且这占用了非常多的时间,所以,Mybatis框架为我们实现了这些操作,业务开发者只需要专注于业务实现,节省开发时间,并且减少数据库操作的错误率。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容