SpringBoot整合MyBatis步骤如下:
1、创建模块
2、勾选需要使用的技术,MyBatis,优于需要操作数据库,因此引入数据库的starter技术和对应的数据库依赖
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>3.0.3</version>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.3.0</version>
<scope>runtime</scope>
</dependency>
3、配置数据源相关配置信息
# 数据源配置信息
spring:
datasource:
druid:
driver-class-name: com.mysql.jdbc.Driver
url: dbc:mysql://localhost:3306/demo?characterEncoding=utf-8
username: root
password: root
4、创建数据库表
create table demo_student_t(
id int not null primary key,
student_name varchar(100) not null,
student_age int not null,
student_num varchar(100) not null,
student_gender varchar(100) not null,
constraint demo_student_t_index unique (student_num)
);
5、创建实体类
@Data
public class Student {
private int id;
private String studentName;
private String studentAge;
private String studentNum;
private String studentGender;
}
6、创建DAO接口,定义操作方法
public interface StudentDAO {
int addStudent(Student student);
}
注意事项
使用SpringBoot2.4.3(不含)之前版本会出现一个小BUG。就是MySQL驱动升级到8以后要求强制配置时区,如果没有配置会出问题,解决方案很简单,驱动URL上面添加对应的设置就行了。
# 数据源配置信息
spring:
datasource:
druid:
driver-class-name: com.mysql.jdbc.Driver
url: dbc:mysql://localhost:3306/demo?characterEncoding=utf-8&serverTimezone=UTC
username: root
password: XXXX
这里设置UTC是全球标准时间,你也可以理解为是英国时间,中国处在东八区,需要在这个基础上加8个小时。这样才能和中国地区的时间对应,也可以修改配置为serverTimezone=Asia/Shanghai,同样可以解决这个问题。