简介

什么是 MyBatis

MyBatis 是一个使用 Java 编写的持久层框架。它封装了 JDBC 操作的很多细节,使开发者只需要关注 sql 语句,而无需关注注册驱动、创建连接、创建 Statement 等繁杂的过程。 使用了 ORM 的思想,屏蔽的 JDBC api 底层细节,实现了对结果集的封装。

三层架构

  • 表现层:展示数据
  • 业务层:处理业务需求
  • 持久层:和数据库交互

持久化

  • 持久化就是将程序的数据在持久状态瞬时状态转化的过程
  • 内存:断电即失

为什么需要 MyBatis

  • 传统 JDBC 太复杂了,简化形成框架
  • SQL 和代码分离,提高了可维护性

持久层技术解决方案

  • JDBC
  • Spring 和 JdbcTemplate
  • Apache 的 DBUtils

传统 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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
public static void main(String[] args) {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
// 1.加载数据库驱动
Class.forName("com.mysql.jdbc.Driver");

// 2.通过驱动管理类获取数据库链接
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8", "root", " root");

// 3.定义 sql 语句 ? 表示占位符
String sql = "SELECT * FROM user WHERE username = ?";

// 4.获取预处理 statement
preparedStatement = connection.prepareStatement(sql);

// 5.设置参数,第一个参数为 sql 语句中参数的序号(从 1 开始),第二个参数为设置的参数值
preparedStatement.setString(1, "loveccknbc");

// 6.向数据库发出 sql 执行查询,查询出结果集
resultSet = preparedStatement.executeQuery();

// 7.遍历查询结果集
while (resultSet.next()) {
System.out.println(resultSet.getString("id") + " " + resultSet.getString("username"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 8.释放资源
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();
}
}
}
}

MaBatis 上手

步骤:搭建环境 –> 导入 MaBatis –> 编写代码 –> 测试

搭建环境

  1. 创建数据库

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    CREATE DATABASE mybatis;

    CREATE TABLE `user`(
    id int PRIMARY KEY,
    username VARCHAR(10),
    password VARCHAR(10)
    );

    INSERT INTO `user` VALUES(1,'admin','admin123');
    INSERT INTO `user` VALUES(2,'root','root123');
  2. 创建 maven 项目

    img

  3. 导入 maven 依赖(pom.xml

    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
    <dependencies>
    <!-- JUnit -->
    <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    </dependency>

    <!-- mybatis -->
    <dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.6</version>
    </dependency>

    <!-- 数据库驱动 -->
    <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.47</version>
    </dependency>

    <!-- lombok -->
    <dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.16</version>
    </dependency>

    </dependencies>
  4. 开始编写代码

    编写核心配置文件(resources/mybatis-config.xml)

    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
    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE configuration
    PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-config.dtd">

    <!--核心配置文件-->
    <configuration>

    <environments default="development">
    <environment id="development">
    <transactionManager type="JDBC"/>
    <dataSource type="POOLED">
    <property name="driver" value="com.mysql.jdbc.Driver"/>
    <property name="url"
    value="jdbc:mysql://localhost:3306/mybatis?useUnicode=true&amp;characterEncoding=utf-8&amp;serverTimezone=UTC"/>
    <property name="username" value="root"/>
    <property name="password" value="root"/>
    </dataSource>
    </environment>
    </environments>

    <!-- 每个 Mapper.xml 都要注册在 MyBatis 核心配置文件中-->
    <mappers>
    <mapper resource="mapper/UserMapper.xml"/>
    </mappers>

    </configuration>
  5. resources 下创建 mapper/UserMapper.xml

    1
    2
    3
    4
    5
    6
    7
    8
    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE mapper
    PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

    <mapper namespace="cn.imzjw.mybatis.mapper.UserMapper">

    </mapper>
  6. 编写 Mabatis 工具类(cn.imzjw.mybatis.utils.MybatisUtils.java

    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
    /**
    * sqlSessionFactory生产sqlSession
    *
    * @author https://blog.imzjw.cn
    * @date 2020/12/23 13:42
    */
    public class MybatisUtils {
    /**
    * 提升作用域
    */
    private static SqlSessionFactory sqlSessionFactory;

    static {
    // 使用MaBatis第一步,获取sqlSessionFactory对象
    try {
    String resource = "mybatis-config.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    } catch (IOException e) {
    e.printStackTrace();
    }
    }

    /**
    * 既然有了SqlSessionFactory,就可以从中获得sqlSession实例。
    * sqlSession完全包含了面向数据库执行SQL命令所需要的所有方法
    *
    * @return
    */
    public static SqlSession getSqlSession() {
    return sqlSessionFactory.openSession();
    }
    }
  7. 创建实体类(cn.imzjw.mybatis.entity.User.java

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    /**
    * @author https://blog.imzjw.cn
    * @date 2020/12/23 14:09
    */
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public class User {
    private int id;
    private String username;
    private String password;
    }
  8. mapper 接口(cn.imzjw.mybatis.mapper.UserMapper.java

    1
    2
    3
    public interface UserMapper {
    List<User> getUserList();
    }
  9. 接口实现类(resources/mapper/UserMapper.xml)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE mapper
    PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

    <mapper namespace="cn.imzjw.mybatis.mapper.UserMapper">

    <!--select查询语句-->
    <select id="getUserList" resultType="cn.imzjw.mybatis.entity.User">
    SELECT * FROM `user`
    </select>

    </mapper>

测试

test 文件下编写测试类(test/java/TestMybatis.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
* @author https://blog.imzjw.cn
* @date 2020/12/23 13:40
*/
public class TestMybatis {

@Test
public void testQuery() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

userMapper.getUserList().forEach(xiaojia -> System.out.println(xiaojia));

sqlSession.close();
}

}

得到结果

1
2
User(id=1, username=admin, password=admin123)
User(id=2, username=root, password=root123)

其它问题

如果出现以下异常

Caused by: org.apache.ibatis.builder.BuilderException: Error parsing SQL Mapper Configuration. Cause: java.io.IOException: Could not find

请在 pom.xml 最后加入资源过滤,没异常就忽略

1
2
3
4
5
6
7
8
9
10
11
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>

我的 pom.xml 完整代码

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
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>cn.imzjw.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>1.0-SNAPSHOT</version>


<dependencies>

<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>

<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>

<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.16</version>
</dependency>

</dependencies>

<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>

</project>