MyBatis
一.原生态jdbc编程中的问题总结
1.创建mysql数据
导入下边的脚本:
sql_table.sql:记录表结构
sql_data.sql:记录测试数据,在实际企业开发中,最后提供一个初始化数据脚本
2.原生态jdbc程序
使用jdbc查询mysql数据库中用户表的记录。
修改pom.xml,引入相关依赖
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>8.0.15version>
dependency>
- 1
- 2
- 3
- 4
- 5
- 6
程序代码:JdbcTest.java使用jdbc的原始方法(未经封装)实现了查询数据库表记录的操作
public class JdbcTest {
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/order?characterEncoding=utf-8", "root", "root");
String sql = "select from user where username = ?"; // 定义sql语句 ?表示占位符
preparedStatement = connection.prepareStatement(sql); // 获取预处理statement
// 设置参数,第一个参数为sql语句中参数的序号(从1开始),第二个参数为设置的参数值
preparedStatement.setString(1, "王五");
resultSet = preparedStatement.executeQuery();// 向数据库发出sql执行查询,查询出结果集
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) {
e.printStackTrace();
}
}
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
- 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
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
3.问题总结
1)、数据库连接,使用时就创建,不使用立即释放,对数据库进行频繁连接开启和关闭,造成数据库资源浪费,影响数据库性能。
设想:使用数据库连接池管理数据库连接。
2)、将sql语句硬编码到java代码中,如果sql 语句修改,需要重新编译java代码,不利于系统维护。
设想:将sql语句配置在xml配置文件中,即使sql变化,不需要对java代码进行重新编译。
3)、向preparedStatement中设置参数,对占位符号位置和设置参数值,硬编码在java代码中,不利于系统维护。
设想:将sql语句及占位符号和参数全部配置在xml中。
4)、从ResultSet中遍历结果集数据时,存在硬编码,将获取表的字段进行硬编码,不利于系统维护。
设想:将查询的结果集,自动映射成java对象。
二.mybatis框架原理
1.mybatis是什么?
mybatis是一个持久层的框架,是apache下的顶级项目。mybatis托管到goolecode下,再后来托管到github下(https://github.com/mybatis/mybatis-3/releases)。
mybatis让程序员将主要精力放在sql上,通过mybatis提供的映射方式,自由灵活生成(半自动化,大部分需要程序员编写sql)满足需要sql语句。 mybatis可以将向 preparedStatement中的输入参数自动进行输入映射,将查询结果集灵活映射成java对象。(输出映射)
2.mybatis框架原理
1、 mybatis配置
SqlMapConfig.xml,此文件作为mybatis的全局配置文件,配置了mybatis的运行环境等信息。
mapper.xml文件即sql映射文件,文件中配置了操作数据库的sql语句。此文件需要在SqlMapConfig.xml中加载。
2、 通过mybatis环境等配置信息构造SqlSessionFactory即会话工厂
3、 由会话工厂创建sqlSession即会话,操作数据库需要通过sqlSession进行。
4、 mybatis底层自定义了Executor执行器接口操作数据库,Executor接口有两个实现,一个是基本执行器、一个是缓存执行器。
5、 Mapped Statement也是mybatis一个底层封装对象,它包装了mybatis配置信息及sql映射信息等。mapper.xml文件中一个sql对应一个Mapped Statement对象,sql的id即是Mapped statement的id。
6、 Mapped Statement对sql执行输入参数进行定义,包括HashMap、基本类型、pojo,Executor通过Mapped Statement在执行sql前将输入的java对象映射至sql中,输入参数映射就是jdbc编程中对preparedStatement设置参数。
7、 Mapped Statement对sql执行输出结果进行定义,包括HashMap、基本类型、pojo,Executor通过Mapped Statement在执行sql后将输出结果映射至java对象中,输出结果映射过程相当于jdbc编程中对结果的解析处理过程。
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-xRpLBkD3-1641215111304)(image/wpsPLJvK4.png)]
三.mybatis入门程序
1.工程结构
1.1 需求
根据用户id(主键)查询用户信息
根据用户名称模糊查询用户信息
添加用户
删除用户
更新用户
1.2 修改pom.xml,引入相关依赖
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.4.6version>
dependency>
- 1
- 2
- 3
- 4
- 5
- 6
1.3 新建log4j.properties日志属性文件
mybatis默认使用log4j作为输出日志信息。
在src文件夹下,创建了resources文件夹,右击选择Mark Directory as --> resources root,在其里面创建log4j.properties文件如下:
# Global logging configuration
# 在开发环境下日志级别要设置成DEBUG,生产环境设置成info或error
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
- 1
- 2
- 3
- 4
- 5
- 6
- 7
修改pom.xml,添加日志依赖
<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
<version>1.2.17version>
dependency>
- 1
- 2
- 3
- 4
- 5
- 6
1.4 新建db.properties属性文件
#mysql
db.username = root
db.password = root
db.jdbcUrl = jdbc:mysql://localhost:3306/order?characterEncoding=utf-8
db.driverClass = com.mysql.jdbc.Driver
- 1
- 2
- 3
- 4
- 5
修改pom.xml,添加mysql依赖
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.38version>
dependency>
- 1
- 2
- 3
- 4
- 5
- 6
1.5 SqlMapConfig.xml核心配置文件
SqlMapConfig.xml是mybatis核心配置文件,配置mybatis的运行环境,数据源、事务等。
在src文件夹下,创建了resources文件夹,在其里面创建SqlMapConfig.xml文件。
首先,先创建mybatis核心配置文件模版
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-15WQGLpl-1641215111309)(image/image-20200713211001576.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-sisJam0u-1641215111310)(image/image-20200713211254836.png)]
DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
configuration>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
要求核心配置文件中,configuration所有配置必须严格按照以下顺序进行编写。[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-5vGnbLOq-1641215111311)(image/image-20210624155159869.png)]
其次,再新建SqlMapConfig.xml核心配置文件
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-L9pu2OGi-1641215111311)(image/image-20200713211431635.png)]
DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<properties resource="db.properties">properties>
<typeAliases>
<package name="com.cm.entity"/>
typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="${db.driverClass}" />
<property name="url" value="${db.jdbcUrl}" />
<property name="username" value="${db.username}" />
<property name="password" value="${db.password}" />
dataSource>
environment>
environments>
<mappers>
<package name=" " />
mappers>
configuration>
- 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
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
1.6 Mapper映射文件
若想在与同名接口同路径下创建Mapper映射文件,需要修改pom.xml。
原因是IDEA编译后默认会把resources下的文件放到target的classpath下,但是src下的只有Java文件编译生成.class文件放入classpath下,其他文件会忽略的,例如.xml文件。
<build>
<resources>
<resource>
<directory>src/main/javadirectory>
<includes>
<include>**/*.xmlinclude>
includes>
resource>
resources>
build>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
首先,先创建mapper映射文件模版
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-OA9QcZRn-1641215111312)(image/image-20200713211001576.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-6BuNuEZ1-1641215111314)(image/image-20200713212326790.png)]
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace=" ">
mapper>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
其次,再新建Mapper映射文件
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ZdYqPANS-1641215111315)(image/image-20200713233247884.png)]
1.7 工程结构

2.根据id查询用户
2.1 创建entity.User类
User.java作为mybatis进行sql映射使用,通常属性名与数据库表字段对应
import java.util.Date;
//属性名称和数据库表的字段对应
public class User {
private int id;
private String username;// 用户姓名
private String sex;// 性别
private Date birthday;// 生日 java.util.Date;
private String address;// 地址
public User() {
}
public User(int id, String username, String sex, Date birthday, String address) {
this.id = id;
this.username = username;
this.sex = sex;
this.birthday = birthday;
this.address = address;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", sex='" + sex + '\'' +
", birthday=" + birthday +
", address='" + address + '\'' +
'}';
}
}
- 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
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
2.2 修改映射文件UserMapper.xml
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.cm.ch01.mapper.UserMapper">
<select id="selectUserById" parameterType="Integer" resultType="User">
select * from user where id = #{id}
select>
mapper>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19