首页 > 解决方案 > 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

这是我整个应用程序中的普遍问题。

标签: mysqlspring-boothibernatejpatimezone

解决方案


经过这么多的研究,我找到了解决方案。

实际上问题是因为

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 设置为杰克逊时区,这解决了这个问题。

希望这个答案可以帮助某人。


推荐阅读