springboot jpa Instant
背景:
springboot,jpa ,达梦
事情的起源是项目使用了Instant类型(天生是UTC时间),然而我们是东八区,前端,后端获取的时间戳都是东八区的时间。
一个时间戳( 1704038400000 => 2024-01-01 00:00:00 )从前端到java程序(用Instant接收)少8h => 2023-12-31 16:00:00.000 ,达梦入库直接入库没做处理。数据库保存的就是 2023-12-31 16:00:00.000 。
Mysql不会存在该问题,因为mysql的驱动支持了Instant类型,会自动加8h。
因此使用下面的代码解决该问题
@Converter(autoApply = true)
public class Instant2DateConverter implements AttributeConverter<Instant, Date> {
@Override
public Date convertToDatabaseColumn(Instant instant) {
return Objects.isNull(instant) ? null : new Date(instant.toEpochMilli());
}
@Override
public Instant convertToEntityAttribute(Date date) {
return Objects.isNull(date) ? null : Instant.ofEpochMilli(date.getTime());
}
}
确保Entity被扫描到,Entity需要被 Spring 或 JPA 提供者(如 Hibernate)扫描到,转换器类才能生效。
@EntityScan("cn.com.sample")