1. Overview
1.概述
Sometimes, when we’re storing dates in MySQL, we realize that the date from the database is different from our system or JVM.
有时,当我们在MySQL中存储日期时,我们发现来自数据库的日期与我们的系统或JVM不同。
Other times, we just need to run our app with another timezone.
其他时候,我们只是需要在另一个时区运行我们的应用程序。
In this tutorial, we’re going to see different ways to change the timezone of MySQL using Spring Boot configuration.
在本教程中,我们将看到不同的方法使用Spring Boot配置改变MySQL的时区。
2. Timezone as a URL Param
2.时区作为一个URL参数
One way we can specify the timezone is in the connection URL string as a parameter.
我们可以指定时区的一种方式是在连接的URL字符串中作为一个参数。
In order to select our timezone, we have to add the connectionTimeZone property to specify the timezone:
为了选择我们的时区,我们必须添加connectionTimeZone属性来指定时区。
spring:
datasource:
url: jdbc:mysql://localhost:3306/test?connectionTimeZone=UTC
username: root
password:
Also, we can, of course, configure the datasource with Java configuration instead.
当然,我们也可以用用Java配置来配置数据源。
We can find more information about this property and others in the MySQL official documentation.
我们可以在MySQL官方文档中找到关于这个属性和其他属性的更多信息。
3. Spring Boot Property
3.Spring Boot属性
Or, instead of indicating the timezone via the connectionTimeZone URL parameter, we can specify the time_zone property in our Spring Boot configuration:
或者,我们可以在Spring Boot配置中指定time_zone property,而不是通过connectionTimeZone URL参数表示时区。
spring.jpa.properties.hibernate.jdbc.time_zone=UTC
Or with YAML:
或者用YAML。
spring:
jpa:
properties:
hibernate:
jdbc:
time_zone: UTC
4. JVM Default Timezone
4.JVM默认时区
And of course, we can update the default timezone that Java has.
当然,我们也可以更新Java的默认时区。
In order to select our timezone, we have to add the property forceConnectionTimeZoneToSession=true in the URL. And then we just need to add a simple method:
为了选择我们的时区,我们必须在URL中添加属性forceConnectionTimeZoneToSession=true 。然后,我们只需要添加一个简单的方法。
@PostConstruct
void started() {
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
}
But, this solution could generate other problems since it’s application-wide. Perhaps other parts of the applications need another timezone. For example, we may need to connect to different databases and they, for some reason, need dates to be stored in different timezones.
但是,这个解决方案可能会产生其他问题,因为它是全应用程序的。也许应用程序的其他部分需要另一个时区。例如,我们可能需要连接到不同的数据库,而它们出于某种原因,需要将日期存储在不同的时区。
5. Conclusion
5.总结
In this tutorial, we saw a few different ways to configure the MySQL JDBC timezone in Spring. We did it with a URL param, with a property, and by changing the JVM default timezone.
在本教程中,我们看到在Spring中配置MySQL JDBC时区的几种不同方法。我们通过URL参数、属性以及改变JVM的默认时区来实现。
As always, the full set of examples is over on GitHub.
一如既往,全套的例子都在GitHub上。