Viv*_*ain 4 mysql timezone hibernate jpa spring-boot
我在 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;
Run Code Online (Sandbox Code Playgroud)
数据库列:
created_on timestamp
Run Code Online (Sandbox Code Playgroud)
服务:
@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;
}
}
Run Code Online (Sandbox Code Playgroud)
存储库
@Repository
public interface IEntityTypeRepository extends CrudRepository<EntityType, Long> {
}
Run Code Online (Sandbox Code Playgroud)
数据库中的日期是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
Run Code Online (Sandbox Code Playgroud)
我在我的appication.properties.
当我删除这个属性时,后端一切正常。后端显示数据库中可用的完美时间。
但现在当响应到达前端时,那时我的日期会转换为 UTC。
就像后端一样,它正在显示 2020-06-03 18:56:14.0,而当涉及到前端时,它会转换为2020-06-02T13:26:14.000+0000.
这对我来说也是一个问题。
因此,经过更多研究,我发现Jackson当对象发送到前端时,默认情况下会将所有日期转换为 UTC。
这个问题的解决办法是
spring.jackson.time-zone=IST
Run Code Online (Sandbox Code Playgroud)
我的数据库和系统时区是 IST,所以我也将 IST 设置为杰克逊时区,这解决了问题。
希望这个答案可以帮助某人。
| 归档时间: |
|
| 查看次数: |
13964 次 |
| 最近记录: |