Mybatis

Mybatis

Mybatis简介

原始jdbc查询操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
@Test
public void selectTest() throws SQLException {
Connection connection = null;
ResultSet resultSet = null;
PreparedStatement statement=null;
try {
//1.注册驱动
Class.forName("com.mysql.jdbc.Driver");
//2.获得数据库连接
connection = DriverManager.getConnection("jdbc:mysql:///demo", "root", "root");
//3.获得statement
statement = connection.prepareStatement("select id,username,password from user");
//4.执行查询
resultSet = statement.executeQuery();
//5.遍历结果集
while (resultSet.next()){
//封装实体
User user = new User();
user.setId(resultSet.getInt("id"));
user.setUsername(resultSet.getString("username"));
user.setPassword(resultSet.getString("password"));
//user实体封装完毕
System.out.println(user);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
//释放资源
resultSet.close();
statement.close();
connection.close();
}
}

原始jdbc插入操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public void insertTest() throws Exception{
Connection connection = null;
ResultSet resultSet = null;
PreparedStatement statement=null;
try {
//1.注册驱动
Class.forName("com.mysql.jdbc.Driver");
//2.获得数据库连接
connection = DriverManager.getConnection("jdbc:mysql:///demo", "root", "root");
//3.获得statement
statement = connection.prepareStatement("insert into user (username,password) values (?,?)");
//模拟实体对象
User user = new User();
user.setUsername("小明");
user.setPassword("1234567");
//设置占位符参数
statement.setString(1,user.getUsername());
statement.setString(2,user.getPassword());
//执行更新操作
statement.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}finally {
//释放资源
statement.close();
connection.close();
}
}

原始jdbc操作分析

原始jdbc开发存在的问题:

  1. 数据库连接创建、释放频繁造成系统资源浪费从而影响系统性能
  2. sql语句在代码中硬编码,造成代码不易维护,实际应用sql变化的可能比较大,sql变动需要改变java代码
  3. 查询操作时,需要手动将结果集中的数据封装到实体中。插入操作时,需要手动将实体的数据设置到sql语句的占位符位置

应对上述问题给出的解决方案:

  1. 使用数据库连接池初始化连接资源
  2. 将sql语句抽取到xml配置文件中
  3. 使用反射、内省等底层技术,自动将实体与表进行属性与字段的自动映射

什么是Mybatis

  1. mybatis 是一个优秀的基于java的持久层框架,它内部封装了jdbc,使开发者只需要关注sql语句本身,而不需要花费精力去处理加载驱动、创建连接、创建statement等繁杂的过程。

  2. mybatis通过xml或注解的方式将要执行的各种 statement配置起来,并通过java对象和statement中sql的动态参数进行映射生成最终执行的sql语句。

  3. 最后mybatis框架执行sql并将结果映射为java对象并返回。采用ORM思想解决了实体和数据库映射的问题,对jdbc 进行了封装,屏蔽了jdbc api 底层访问细节,使我们不用与jdbc api打交道,就可以完成对数据库的持久化操作

Mybatis快速开始


Mybatis
http://example.com/2023/09/12/SSM/mybatis/Mybatis/
作者
zhuixun
发布于
2023年9月12日
许可协议