SpringBoot整合MyBatis

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,同样可以解决这个问题。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

桑落兮

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值