mysql - Spring Boot JPA 应用程序中的时区问题
问题描述
我在我的 spring boot jpa 应用程序中面临日期时间问题。
例如,在我的数据库中,我有一列created_on
包含2019-07-11 09:30:00
日期。当我获取这条记录时,JPA 会转换为 UTC。
表示日期2019-07-11 09:30:00
转换为2019-07-11 05:00:00
.
我的系统时间在 IST 中,日期也保存在 IST 中的数据库中。
我正在使用mysql数据库。
在我的实体中
private Date createdOn;
数据库列:
created_on timestamp
服务:
@Service
@Transactional(readOnly = true)
public class EntityTypeService {
@Autowired
private IEntityTypeRepository entityTypeRepository;
public EntityType findById(Long id) {
EntityType entityType = entityTypeRepository.findById(id).orElse(new EntityType());
System.out.println(entityType.getCreatedOn());
return entityType;
}
}
存储库
@Repository
public interface IEntityTypeRepository extends CrudRepository<EntityType, Long> {
}
数据库中的日期是2019-07-11 09:30:00
但是当我在服务上打印它时,System.out.println(entityType.getCreatedOn());
它给了我2019-07-11 05:00:00
。
这是我整个应用程序中的普遍问题。
解决方案
经过这么多的研究,我找到了解决方案。
实际上问题是因为
spring.jpa.properties.hibernate.jdbc.time_zone=UTC
我在我的appication.properties
.
当我删除此属性时,后端一切正常。后端显示数据库中可用的完美时间。
但是现在当响应来到前端时,那时我的日期被转换为 UTC。
就像它显示的后端一样 2020-06-03 18:56:14.0
,当涉及到前端时它转换为2020-06-02T13:26:14.000+0000
.
这对我来说也是一个问题。
因此,经过更多研究后,我发现Jackson
当对象发送到前端时,默认情况下会将所有日期转换为 UTC。
这个问题的解决方案是
spring.jackson.time-zone=IST
我的数据库和系统时区是 IST,所以我也将 IST 设置为杰克逊时区,这解决了这个问题。
希望这个答案可以帮助某人。
推荐阅读
- sql - 用作“IN”比较的列表为空时出错
- bash - 是否可以直接在 bash 中为 git repo 输入密码?
- javascript - 带有更多菜单的 jQuery 动态选项卡
- aws-lambda - aws events put-targets 响应为正,但未添加触发器
- graphql - 有没有办法用原始数据预加载 Apollo 的内存缓存?
- java - Java 检查 Stack 是否包含某个类
- android - 如何从活动更新片段中的视图
- angular - Angular+2:如何在同一个 index.html 中构建两个不同的包?
- html - 需要实现手风琴以仅在单击时展开子 div 并默认保持折叠状态
- javascript - 格式化日期并获取与今天的日期和时间相比的差异