Mybatis学习

前言

学习。


环境搭建

使用IDEA新建Spring Boot项目,选择安装Spring Web、Thymeleaf和MyBatis框架,由于使用的是JDK8,SpringBoot不支持JDK8,因此选用SpringBoot2。

简单编写控制器框架后,在虚拟机中开启MySQL镜像:

1
docker run -id --name mysql -p 3306:3306 -e MYSQL_ROOT_PASSWORD=root mysql

创建数据库

创建测试用数据库:

1
2
3
create database mybatis DEFAULT CHARSET utf8 COLLATE utf8_general_ci;
use mybatis;
create table data(id int(11) not null auto_increment, name varchar(255), password varchar(255), email varchar(255), primary key (id))engine=innodb default charset=utf8 COLLATE=utf8_general_ci;

连接数据库

设置数据库连接池,这里安装Druid:

1
2
3
4
5
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.17</version>
</dependency>

然后修改配置文件:

1
2
3
4
5
spring.datasource.url=jdbc:mysql://192.168.88.129:3306/mybatis?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root

spring.datasource.type=com.alibaba.druid.pool.DruidDataSource

报错:

1
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver

没有MySQL的相关驱动,安装依赖:

1
2
3
4
5
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.0.32</version>
</dependency>

官方文档中可以找到MyBatis的使用方法,首先根据数据库结构定义对应的数据类:

1
2
3
4
5
6
7
8
public class DataDao {
private int id;
private String name;
private String password;
private String email;

// Getter和Setter们
}

然后定义查询用的SQL语句:

1
2
3
4
5
@Mapper
public interface DataMapper {
@Select("select * from data")
List<DataDao> selectAll();
}

为了使用整个映射接口,还需要借助Spring的依赖注入机制:

1
2
3
4
5
6
7
8
9
10
11
12
13
@Service
public class DataService {
private DataMapper dataMapper;

@Autowired
public DataService(DataMapper dataMapper) {
this.dataMapper = dataMapper;
}

public List<DataDao> selectAll() {
return dataMapper.selectAll();
}
}

虽然依赖注入IDEA会提示错误,但是实际上不影响,可以修改警告等级关掉它,最后在控制器中查询并输出:

1
2
3
4
5
6
7
8
9
@Autowired
private DataService dataService;

@GetMapping("/main")
public String main(Model model){
List<DataDao> data = dataService.selectAll();
model.addAttribute("data", data);
return "main";
}

模板文件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
<title>Main</title>
</head>
<body>
<h1>main</h1>
<p th:each="data: ${data}">
<span th:text="${data.id}"></span>
<span th:text="${data.name}"></span>
<span th:text="${data.password}"></span>
<span th:text="${data.email}"></span>
</p>
</body>
</html>

可以看到查询成功。


参考

https://blog.csdn.net/syc000666/article/details/128108711


Mybatis学习
http://yoursite.com/2023/04/11/Mybatis学习/
作者
Aluvion
发布于
2023年4月11日
许可协议