mysql数据库中timestap类型遇到的坑
springboot2.2.6 mybatis2.1.0 依赖如下:
<dependencies>
<!--连接数据库的驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!--mybatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.0</version>
</dependency>
<!--junit-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
DDL(这里create_time字段使用了timestamp时间戳类型):
CREATE TABLE `user` (
`id` int NOT NULL AUTO_INCREMENT COMMENT '主键',
`name` varchar(20) NOT NULL DEFAULT '' COMMENT '用户名',
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '用户创建时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
对应的pojo如下:
public class User {
private Integer id;
private String name;
private Date create_time;
//省略getter/setter、toString方法
}
将Date类型的数据插入到MySQL中的时间戳类型
注意:插入数据库的时候 mybatis会自动将Date转换为MySQL中的timestamp类型
@Test
public void insertUser(){
User user = new User();
user.setName("李四");
Date time = Calendar.getInstance().getTime(); //Fri Jul 31 19:13:18 CST 2020
user.setCreate_time(time);
//插入数据库的时候 mybatis自动将Date转换为MySQL中的timestamp类型
userDao.insert(user);
}
这里出现了一个神奇的现象,竟然少了13个小时!为什么数据库中插入的时间怎么和本地系统时间不一样呢?
结论:MySQL默认采用它自带那个时区的时间,我们需要手动指定时区为我们国家的时区,在application.properties配置文件中加入:
意思是在格林威治时区上加上8,变为东八区,即北京时间为准。+号在URL中必须被编码,成了%2B。
再次插入数据:
@Test
public void insertUser(){
User user = new User();
user.setName("王五");
Date time = Calendar.getInstance().getTime(); //Fri Jul 31 19:13:18 CST 2020
user.setCreate_time(time);
//插入数据库的时候 mybatis自动将Date转换为MySQL中的timestamp类型
userDao.insert(user);
}
问题解决!