如果应用程序使用另一个时区而不是MySQL,则Hibernate会保存/检索日期减去日期 [英] Hibernate saves/retrieves date minus day if application uses another timezone than MySQL
问题描述
我在MACHINE_A上的tomcat上启动了一个应用程序,时区GMT + 3.
I have an application started on tomcat on MACHINE_A with timezone GMT+3.
我使用远程MySQL服务器在MACHINE_B上启动时区UTC。
I use remote MySQL server started on MACHINE_B with timezone UTC.
我们使用spring-data-jpa来表示持久性。
We use spring-data-jpa for persistence.
作为问题的一个例子,我将展示存储库:
As an example of the problem, I will show the repository:
public interface MyRepository extends JpaRepository<MyInstance, Long> {
Optional<MyInstance> findByDate(LocalDate localDate);
}
如果我通过localDate 2018-09-06
,我得到的实体的日期是 2018-09-05
(前一天)
If I pass localDate for 2018-09-06
, I get entities where the date is 2018-09-05
(previous day)
在日志中我看到:
2018-09-06 18:17:27.783 TRACE 13676 --- [nio-8080-exec-3] o.h.type.descriptor.sql.BasicBinder : binding parameter [1] as [DATE] - [2018-09-06]
我搜索了很多这个问题并找到了几篇内容相同的文章(例如 https://moelholm.com/2016/11/09/spring-boot-controlling-timezones-with-hibernate/ )
I googled that question a lot and found several articles with the same content(for example https://moelholm.com/2016/11/09/spring-boot-controlling-timezones-with-hibernate/)
所以,我有以下 application.yml
:
spring:
datasource:
url: jdbc:mysql://localhost:3306/MYDB?useUnicode=true&characterEncoding=utf8&useSSL=false&useLegacyDatetimeCode=false&serverTimezone=UTC
username: root
password: *****
jpa:
hibernate:
naming:
physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
properties:
hibernate:
show_sql: true
use_sql_comments: true
format_sql: true
type: trace
jdbc:
time_zone: UTC
但它没有帮助。
我们使用以下连接器:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.12</version>
</dependency>
如何解决我的问题?
我尝试使用相同的时区运行这两个应用程序。在这种情况下,一切都按预期工作。
I tried to run both applications with the same time zone. In this case, everything works as expected.
我试图使用MySQL驱动程序6.0.6版本,但它不会改变任何东西。
I tried to use MySQL driver 6.0.6 version but it doesn't change anything.
推荐答案
如果你正在使用 LocalDate
在Java中,你应该在MySQL中使用 DATE
列。这样问题就解决了。
If you're using LocalDate
in Java, you should use a DATE
column in MySQL. This way the problem will be solved.
如果使用 LocalDateTime
,请尝试在Spring Boot中设置如下属性:
If you use LocalDateTime
, try setting the property like this in Spring Boot:
spring.jpa.properties.hibernate.jdbc.time_zone=UTC
有关更详细的说明,请查看这篇文章。您可以在我的高性能Java持久性GitHub存储库,运行正常。
For a more detailed explanation, check out this article. You can find a test case in my High-Performance Java Persistence GitHub repository which works just fine.
这篇关于如果应用程序使用另一个时区而不是MySQL,则Hibernate会保存/检索日期减去日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!