缘由:在使用Calendar
作为字段类型时,每进行一次findById()
操做返回的数据的值都比实际值要大一点。更新后再调用查询,还会再大一点。也就是说:若是咱们用Calendar
作为字段类型,那么该字段会在程序运行时会静悄悄的增大。java
示例代码很简单:咱们只须要准备两个类,一个实体,一个数据访问对象。mysql
Student.javagit
package com.example.demo; import org.hibernate.annotations.CreationTimestamp; import javax.persistence.*; import java.sql.Timestamp; import java.util.Calendar; @Entity public class Student { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; @CreationTimestamp private Calendar applyTime; @CreationTimestamp private Timestamp applyTimestamp; // 省略构造函数及setter/getter }
为了测试代码更简单,咱们为applyTime
及applyTime
加入CreationTimestamp
注解。让其自动生成。github
删除自动时间戳并不会影响测试结果
package com.example.demo; import org.springframework.data.repository.CrudRepository; public interface StudentRepository extends CrudRepository<Student, Long> { }
package com.example.demo; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @SpringBootTest @RunWith(SpringRunner.class) public class StudentRepositoryTest { private static final Logger logger = LoggerFactory.getLogger(StudentRepositoryTest.class); @Autowired StudentRepository studentRepository; @Test public void test() { Student student = new Student(); studentRepository.save(student); Student student1 = studentRepository.findById(student.getId()).get(); System.out.println(student1.getApplyTime().getTimeInMillis()); System.out.println(student1.getApplyTimestamp().getTime()); } }
结果以下:spring
1566119784000 1566090984000
可见,使用Calendar
类型获取值较Timestamp
类型的自动增长了。若是此时保存实体,则此增长的值将被自动写入数据表。sql
github: https://github.com/mengyunzhi...
stackoverflow: https://stackoverflow.com/que...数据库
Calendar
类型在spring-boot 2.1.7版本中应该暂时弃用,转而使用Timestamp
或LocalDateTime
。segmentfault
若是你也是在版本的基础上升的级,那么须要处理同样时区的问题。由于一样的数据Calendar
与Timestamp
最终存到数据库中的值是不一致的。其中Calendar
存的是加入了时区之后的值,Timestamp
存的是原始值:app
幸运的是:两个类型映射到mysql
中的类型均是datetime
,这为咱们下降了升级的难度。函数
@CreationTimestamp private Timestamp applyTime;
update student set apply_time = SUBTIME(apply_time, '8:00');