我使用 Spring JPA 和 Hibernate 5.3 创建了一个 Spring Boot 2.x 应用程序。我正在使用 MySql 5.7。由于“我的数据库”中的“日期时间”列具有 6 位精度,因此我想在将值存储在数据库中之前将应用程序中的日期截断为微秒。
事实上,如果我不这样做,当我有一个像 2020-01-31T22:59:59.999999999Z
这样的日期时,在 MySql 中将被持久化为 2020-01 -31T23:00:00.000000Z
当然我不想要这个!
我在我的应用程序中使用 java.time.Instant。我正在寻找一种巧妙的方法来为整个应用程序完成此任务。 我很矛盾是否使用自定义 Hibernate 类型或其他类型。我想要一些提示来指引我正确的方向。
最佳答案
truncatedTo()
当您知道时,这很容易:使用您正在使用的日期时间类的 truncatedTo
方法(可能是 Instant
或 OffsetDateTime
)。例如:
Instant pointInTime = Instant.parse("2020-01-31T22:59:59.999999999Z");
System.out.println("Original instant: " + pointInTime);
Instant truncated = pointInTime.truncatedTo(ChronoUnit.MICROS);
System.out.println("Truncated to microseconds: " + truncated);
输出是:
Original instant: 2020-01-31T22:59:59.999999999Z Truncated to microseconds: 2020-01-31T22:59:59.999999Z
不过,它不会在您的应用程序中自动运行。
关于java - Hibernate 5.3,坚持 java.time.* 截断到微秒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58172984/