什么是Mybatis

MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。

持久化

  • 因为内存有断电即失的特性,所以需要进行数据持久化
  • 持久化就是将程序的数据在持久状态和瞬时状态转化的过程

持久层

持久层,可以理解成数据保存在数据库或者硬盘一类可以保存很长时间的设备里面,不像放在内存中那样断电就消失了,也就是把数据存在持久化设备上

Mybatis的简单使用(Maven项目)

pom文件引入jar包

1
2
3
4
5
6
7
8
9
10
11
12
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>

创建工具类

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
package cn.com.scitc.mybatis.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MybatisUtil {
private static SqlSessionFactory sqlSessionFactory;

static {
InputStream inputStream = null;
try {
//用输入流来读取xml文件
inputStream = Resources.getResourceAsStream("mybatis-config.xml");
} catch (IOException e) {
e.printStackTrace();
}
//创建SqlSession工厂
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}

public static SqlSession getSqlSession(){
//创建并返回SqlSession
return sqlSessionFactory.openSession();
}
}

创建实体类

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
package cn.com.scitc.model;

public class User {
private Integer id;
private String name;
private String mobile;

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getMobile() {
return mobile;
}

public void setMobile(String mobile) {
this.mobile = mobile;
}
}

创建mybatis配置文件

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
<?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">
<!-- JDBC配置 -->
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/webapp1901"/>
<property name="username" value="root"/>
<property name="password" value="lishuang001219"/>
</dataSource>
</environment>
</environments>
<mappers>
<!-- 绑定Mapper配置文件 -->
<mapper resource="UserMapper.xml"/>
<!-- resource下的Mapper资源存在多层目录结构时的写法 -->
<mapper resource="cn/com/scitc/webapp1901/mapper/UserMapper.xml"/>
</mappers>
</configuration>

创建Mapper接口文件

1
2
3
4
5
6
7
package cn.com.scitc.test.mapper;

import cn.com.scitc.test.pojo.User;

public interface UserMapper {
public User findById(Integer id);
}

创建Mapper配置文件

UserMapper.xml

1
2
3
4
5
6
7
8
9
10
11
12
<?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">
<!-- namespace命名空间:对应一个Mapper接口 -->
<mapper namespace="cn.com.scitc.mapper.UserMapper">
<!-- sql语句 -->
<!-- id对应接口中定义的方法 resultType表示结果集类型 -->
<select id="selectUser" resultType="cn.com.scitc.model.User">
select * from user where id = #{id}
</select>
</mapper>

创建Dao文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package cn.com.scitc.test.dao;

import cn.com.scitc.test.mapper.UserMapper;
import cn.com.scitc.test.pojo.User;
import cn.com.scitc.test.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;

public class UserDao implements UserMapper{

public User findById(Integer id) {
//获取SqlSession
try(SqlSession session = MybatisUtils.getSqlSession()){
//获取Mapper,执行其中方法
UserMapper mapper = session.getMapper(UserMapper.class);
return mapper.findById(id);
}
}
}

编写测试类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package cn.com.scitc.test;

import cn.com.scitc.test.dao.UserDao;
import cn.com.scitc.test.pojo.User;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

class UserDaoTest {

@Test
void findById() {
UserDao userDao = new UserDao();
User user = userDao.findById(1);
System.out.println(user.getName());
Assertions.assertEquals("张三",user.getName());
}
}

项目基本结构

mybatis-generator的简单使用

注:此插件主要用于自动生成实体类、Mapper接口和Mapper配置文件。mybatis配置文件和Dao层文件需要根据实际应用场景对照生成的文件自行编写

编写pom文件

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
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>

<!-- 添加插件 -->
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.4.0</version>
<executions>
<execution>
<id>Generate MyBatis Artifacts</id>
<goals>
<goal>generate</goal>
</goals>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.5</version>
</dependency>
</dependencies>
<configuration>
<!-- 设置生成的文件覆盖源文件 -->
<overwrite>true</overwrite>
</configuration>
</plugin>

编写mybatis-generator配置文件

generatorConfig.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<!DOCTYPE generatorConfiguration PUBLIC
"-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<context id="simple" targetRuntime="MyBatis3Simple">
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/webapp1901" userId="root" password="lishuang001219"/>
<!--实体存放位置-->
<javaModelGenerator targetPackage="cn.com.scitc.webapp1901.pojo" targetProject="src/main/java"/>
<!--Mapper.xml存放位置-->
<sqlMapGenerator targetPackage="cn.com.scitc.webapp1901.mapper" targetProject="src/main/resources"/>
<!--Mapper接口存放位置-->
<javaClientGenerator type="XMLMAPPER" targetPackage="cn.com.scitc.webapp1901.mapper" targetProject="src/main/java"/>
<!--需要生成的表-->
<table tableName="student" />
</context>
</generatorConfiguration>

双击一键生成代码